Click here to Skip to main content
15,911,482 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void button2_Click(object sender, EventArgs e)
        { 
           if (textBox1.Text.Trim().Length == 0)
                MessageBox.Show("Please fill this area first");
            
            else
            {
                SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AG_DB;Integrated Security=True");
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Musteri where ID = '" + textBox1.Text + "'", con);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                textBox1.Text = dt.Rows[0][0].ToString();
                textBox2.Text = dt.Rows[0][1].ToString();
                textBox3.Text = dt.Rows[0][2].ToString();
                textBox4.Text = dt.Rows[0][3].ToString();
                textBox5.Text = dt.Rows[0][4].ToString();
                textBox6.Text = dt.Rows[0][5].ToString();
                textBox7.Text = dt.Rows[0][6].ToString();
                textBox8.Text = dt.Rows[0][7].ToString();
            }
        }

this is my code that reads data from sqlserver and fills all textboxes using textbox1. I need an exception that warns me when i write something on textbox1 that doesn't exist on my sql ID Column. How can i do that?
Posted

Confirm that you have a data row in the data table;
C#
if(dt.Rows.Count > 0)
{
textBox1.Text = dt.Rows[0][0].ToString();
...
}
else
 
Share this answer
 
Comments
Member 10587827 8-Jan-15 5:32am    
Thank you!
Why textbox1? Use a dropdownlist instead. Populate that dropdownlist with the ids from the database table. e.g.:
Populate Dropdownlist from Database - ASP.NET[^]
In this way, you do not need to check the user's input against the database.
Read more: DropDownList Class[^]
 
Share this answer
 
v2
0) Use using statement.
1) Use a parameterized command.
2) Don't use a DataAdapter or DataTable.
3) Use a DataReader and just try reading from it, it will have data or it won't.
 
Share this answer
 

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