0

I am trying the following in order to display the sql table data inside a gridview

try
    {
        SqlConnection xconn = new SqlConnection();
        xconn.ConnectionString = @"Data Source=servername;Integrated Security=True;Initial Catalog=master";
        xconn.Open();

        string s = "select * from tablename";
        SqlCommand ycmd = new SqlCommand(s,xconn);
        SqlDataReader dr = ycmd.ExecuteReader();

        gridview.DataSource = dr;
        gridview.DataBind();
    }
    catch (Exception)
    {
        lblresult.Text = "Cannot connect to SQL";
    }

I keep getting an exception. What am i doing wrong?

6
  • 1
    What is the exception you are receiving? Commented Nov 3, 2011 at 4:00
  • I am thinking you cannot bind a datareader to a grid. Commented Nov 3, 2011 at 4:02
  • What line is throwing the exception, and what is the exception? Commented Nov 3, 2011 at 4:02
  • 1
    @Brettski - you can bind to a DataReader(). There's an example (similar to this code) on this page: support.microsoft.com/kb/307860 Search for ExecuteReader() - it's about halfway down. Commented Nov 3, 2011 at 4:05
  • 1
    I see [Initial Catalog=master] in your connection string. Is your table in the system [master] database? Just confirming. When you trace, does the exception get thrown at the line .Open() or further below? Commented Nov 3, 2011 at 5:58

2 Answers 2

1

change the Catch section with

catch (Exception ex)
{
    lblresult.Text = ex.Message &"\n" & ex.StackTrace;
}

Now you will get a valid exception description. use that to fix it yourself... :)

If not, post the detailed exception information from the lblresult.Text in your post.

Sign up to request clarification or add additional context in comments.

Comments

0

You must fill the request result in a varible which you can use as itemsource.

GridView.ItemsSource = ContainerClass.AllItems;

The ContainerClass is a help class and contains a IEnumerable AllItems variable. The gridview can show the values on this way!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.