5
Answers

Advanced Search using textbox in C# Windows form application

Sumit Dwivedi

Sumit Dwivedi

8y
608
1
Hi Folks,
 
I am trying to search records in the database based on input value in Textbox (txtStudentName is the one) and want to populate the records into datagrid control On the form load, i am populating the datagrid with the full table. What actually i want is that as soon as i click search button, the datagrid should be filled with the search result and the full table should not come. I have written the below piece of logic for the same-->
 
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
//row.Selected = true;
break;
}
}
}
 
Now my doubt is how should i populate the datagrid with this search results 
 
 
 
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=Student;Integrated Security=True";
string sql = "SELECT * FROM Student_Detail";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
connection.Open();
DataSet ds = new DataSet();
dataadapter.Fill(ds, "Student_Detail");
connection.Close();
dataGridView1.DataSource = ds.Tables[0];
}
private void btnSearch_Click(object sender, EventArgs e)
{
 
if (txtStudentName.Text != " ")
{
string searchValue = txtStudentName.Text;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
//row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}

Answers (5)