Reputation: 57
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.
Upvotes: 0
Views: 508
Reputation: 74605
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 ..
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
}
View
should be called view
because it is a local member, not a publicly accessible class level propertyUpvotes: 2
Reputation: 63126
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
Upvotes: 0