简体   繁体   中英

DataGridView not showing table C#

My data grid view isn't showing the data. I want it to show whole table at runtime and a search option to search specific rows.

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\source\repos\phoneBookwin\phoneBookwin\Database1.mdf;Integrated Security=True");
con.Open();

using (SqlCommand com = new SqlCommand("select * from Contacts"))
{
    using (SqlDataAdapter db = new SqlDataAdapter("select * from Contacts", con))
    {
        DataTable View = new DataTable();
        db.Fill(View);
    }
}

and this is for searching specific contact

private void search_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\source\repos\phoneBookwin\phoneBookwin\Database1.mdf;Integrated Security=True");
    con.Open();
    SqlDataAdapter cmd = new SqlDataAdapter("Select * from Contacts where Name = '"+searchBox.Text+"'",con);
    DataTable View = new DataTable();
    cmd.Fill(View);
    con.Close();
}

The data gridview isn't showing anything whether I click the search button or not.

Your code never assigns the resulting DataTable you filled, to a datagridview; it just fills it then throws it away. You need a call to someDataGridView.DataSource = View after the call to Fill

If, after you do this the datagridview is still blank, it is likely no data was downloaded to the datatable. Check you're connected to the correct database and that the table has data. If you don't see the columns you expect, check that the datagridview's AutoGenerateColumns setting is true

Other points, please..

  • ..stop writing SQL in the way you currently are, concatenating the value in from a textbox - not only will it fall sort of someone searches for the name O'Connor it also puts you at risk of the most common form of hacking applicable to database software. Read http://Bobby-tables.com - your code should look more like:
    using(var da = new SqlAdapter("SELECT * FROM t WHERE c LIKE @p") {
      da.SelectCommand.Parameters.Add("@p", SqlDbType.VarChar, 4000).Value = textbox.Text;
      //fill etc
    }
  • ..make yourself familiar with C# naming conventions. View should be called view because it is a local member, not a publicly accessible class level property

There are a number of issues with your example the primary issue is what you are not yet assigning the table as a source to a Grid as mentioned by Calus Jard.

Additionally, your query with user input being concatenated into a SQL query is very dangerous, I would recommend using a parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM