Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to load the database table data on datagridview.

i have created a win application which insert data from textbox to database on button click event.

but now i want to retrieve particular ID info rows data in datagridview.

for example if we give ID in textbox it should retrieve that data in datagriedview.

can anyone help me with sample code.


Thanks Regards
sam.198979
Posted

1 solution

There are a number of ways to do this, one is to issue the same SELECT query you have been doing to retrieve all the rows, but to add a WHERE clause:
SQL
SELECT * FROM myTable WHERE ID=17
(only preferably, with a parameterised query:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myDataGridView.DataSource = dt;
        }
    }

But there is another way, which can be a lot more flexible (and much quicker from the user POV) - use a DataView as well:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myClassLevelDataView = new DataView(dt);
        myDataGridView.DataSource = dv;
        }
    }
Then when you want to change it, you just set the RowFilter property of the DataView:
C#
myClassLevelDataView.RowFilter = "Text LIKE '%" + myTextBox.Text + "%'";
And magic happens! :laugh:
 
Share this answer
 
Comments
Shahin Khorshidnia 18-Jun-13 5:24am    
Perfect +5
sam.198979 18-Jun-13 7:47am    
i have 3 tables

want to display other tables data in same datagridview.

can u help me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900