C # windows forms / underlying data grid

One of the problems I run into with C # is that there is so much information on the internet that I am having trouble finding the right answer to the most basic questions.

I'm trying to do something simple: I have a button, I click on it, it queries the database and populates the datagrid in my window form.

    private void button1_Click(object sender, EventArgs e)
    { 
        SqlConnection c = new SqlConnection("Data Source = (local); Integrated Security = true; Initial Catalog = pubs;  "); 

        c.Open();
        // 2
        // Create new DataAdapter
        SqlCommand cmd = c.CreateCommand();
        cmd.CommandText = @" SELECT * FROM Authors ";
        SqlDataReader reader = cmd.ExecuteReader();

        dataGridView1.DataSource = reader;
        dataGridView1.DataBind();
    }

      

Error 1 'System.Windows.Forms.DataGridView' does not contain a definition for "DataBind" and no extension method "DataBind" that takes a first argument of type "System.Windows.Forms.DataGridView" ....

I am probably missing "using directive", but which one? Several google searches tell me how to bind a Yahoo rss feed to a gridview, or provide various obscure details about "directive usage".

Perhaps I am using the SqlDataReader incorrectly. Should I be using SqlAdapter instead? What's up with all the good basic online tutorials for Windows C # forms? I found a couple of great tutorials a few months ago, but they seem to have lost their pager and I can no longer find them using basic google searches.

+2


source to share


2 answers


Try this instead:

using (SqlConnection conn = new SqlConnection("your connection string"))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(@"SELECT * FROM Authors", conn))
    {
        using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
        {
            DataTable dt = new DataTable();
            adap.Fill(dt);
            dataGridView1.DataSource = dt;
        }
    }
}

      

The DataGridView does not have a DataBind () method because it is not needed. Setting the DataSource property handles the binding for you. The using () blocks will automatically close and destroy everything for you.

Note : you must replace "your connection string" with a valid connection string. I left yours from my sample to avoid horizontal scrollbars and I'm not sure if yours is valid anyway. When you run your code using a connection string, you might get a runtime error. www.connectionstrings.com is a great resource for determining a valid connection string.

Update : instead of nested use () blocks, you can also do it like this:

using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand(@" SELECT * FROM Authors", conn))
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
    conn.Open();
    DataTable dt = new DataTable();
    adap.Fill(dt);
    dataGridView1.DataSource = dt;
}

      



I prefer the nested style, but it's half one, six dozen others for me. Typically, I would encapsulate such code into a class (called "DataGetter" or whatever) with a static method like:

public static DataTable GetData(string query)
{
    // do all the connecting and adapting and filling and so forth
}

      

so that the code in the click on the button is as simple as:

dataGridView1.DataSource = DataGetter.GetData("SELECT * FROM AUTHORS");

      

However, I would not do this in any performance critical section of my code, as sometimes you want to keep the SqlCommand object (and its SqlParameter collection) between calls. You don't need to persist SqlConnection objects between calls, thanks to pooling (you don't really want to support them under any circumstances).

+2


source


You are missing a using directive; it's just that WinForms DataGridView doesn't have a DataBind method . Just assigning the DataSource is enough to get the binding; you also don't need to call the method.



However, I don't think you can assign the SqlDataReader as a DataSource. According to the DataSource Property Documentation on MSDN , the DataSource must be IList, IListSource, IBindingList, or IBindingListView. You might most likely have to load data into a DataTable or DataSet (or an object data source populated with an object-relational mapper) and use that as a DataSource.

+4


source







All Articles