Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello sir,

I am creating in windows form appliacation in C#.
I created three labels first name,middle name,last name. Infront of those labels there will be textboxes & one button below called "Search" Button. I had created a table in which fields called first name,middle name,last & inserted values. Now in the output window ,if i give a firstname & hit a search button,the data as to be retrived into other textboxes-middle name,last name.

this my code,i think we need to change the query:
C#
//search button below.
 private void button1_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True");
            con.Open();
            com = new SqlCommand("select middle,last from  Table2 where first= '"+ textBox1.Text.Trim()+"'",con);
            rdr = com.ExecuteReader();
            bool temp = false;
            while (rdr.Read())
            {

                //textBox1.Text = rdr.GetString(0);
                textBox1.Text = rdr[0].ToString().Trim();//ToString();// GetString(1);
                textBox2.Text = rdr[1].ToString().Trim();
                //textBox4.Text = rdr.GetString(3);
                //textBox5.Text = rdr.GetString(4);
                //textBox6.Text = rdr.GetString(5);
                //textBox7.Text = rdr.GetString(6);
                //textBox8.Text = rdr.GetString(7);
                //textBox9.Text = rdr.GetString(8);
                //textBox10.Text = rdr.GetString(9);
                temp = true;

            }
            
            if (temp == false)
                MessageBox.Show("not found");
            con.Close();

            con.Open();
            ds = new DataSet();
            da = new SqlDataAdapter("select * from Table2", con);
            da.Fill(ds, "Table2");
            con.Close();


        }
How to achieve this sir.
please do help me

Thanks
Pradeep CBZ
Posted
Updated 14-Mar-12 4:21am
v2

1 solution

First off, it is best to use a parameterised query rather than concatenating strings like this
C#
com = new SqlCommand("SELECT middle, last FROM  Table2 WHERE first = @firstName", con);
com.Parameters.AddWithValue(@firstName", textBox1.Text.Trim());


Then you can use dr.HasRows instead of using a temp bool variable like this:-
C#
if(dr.HasRows)
{
  while(dr.Read())
  {
    txtLast.Text = (string)dr[0];
    txtMiddle.Text = (string)dr[1];
  }
  dr.Close();
}
else
{
  MessageBox.Show("Not found !");
}
 
Share this answer
 
v2
Comments
Pradeep CBZ 18-Mar-12 15:05pm    
Thank you sir for your replay,I will try it...I will let u know.

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