Search In Database on value with some Parameters by Textbox and if found bring its correspond Data and if not give message said No Data exist ???????
my scenario in brief is
i have a form include DataGridView and Textbox and button when i search on something as example by ProductID , then my DataGridView bring the Data and bind it to interface okay
so if i entered some non exist data on database its back to me with bind empty row so i wanna deal with that in professional way and give message include that no rows with this ProductID
i tried that code but wont work the second IF condition i didn't know why so i need help
string connstring = ConfigurationManager.AppSettings.Get("GrandMotorsConnection");
string query = @"SELECT ProductID,ProductName,ProductQuantity,ProductPhoto,Note FROM Products WHERE ProductID= @ProductID ";
SqlConnection conni = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand(query, conni);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("@ProductID", SqlDbType.Int);
cmd.Parameters["@ProductID"].Value = Convert.ToInt32(ProductIDTextBox.Text);
DataSet ds = new DataSet();
conni.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
MessageBox.Show(" Rown found and bind safely", "ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// i want this condition is happened if my search was on empty Parameters or Non exist data ;) thats all
MessageBox.Show("Not Found ", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
conni.Close();
da.Fill(ds, "Products");
}
Kirtan PatelPosted Oct 13, 2009, 1:11 PM
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand comm = new SqlCommand("select * from products where ProductID=@ProductId", con);
comm.Parameters.AddWithValue("@ProductId", txtSearch.Text);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
else
{
dataGridView1.DataSource = null;
MessageBox.Show("No Record Exist!!");
}
}
Kirtan PatelPosted Oct 14, 2009, 12:21 AM
to format the code correctly :)
Hesham HemdanPosted Oct 13, 2009, 5:32 PM