我当前正在进行一项活动,当用户输入在数据库中找不到的姓氏时,我的搜索按钮未显示我的警报消息。如果在数据库中找到姓氏,它已经在显示记录。并且我打算在记录显示时放一个删除按钮。而且我不知道该怎么做。只是要求一点提示。谢谢。
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBcon"].ConnectionString))
{
try
{
con.Open();
string Sql = "SELECT * FROM contacts WHERE LastName LIKE '" + txtbx_search.Text + "%'";
MySqlDataAdapter da = new MySqlDataAdapter(Sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('No record with that last name found!')", true);
}
finally
{
con.Close();
}
在您的代码中,Allert包含在catch
块中,仅当它们有任何错误时才执行。但是在所需的情况下,您需要检查数据库中记录集中的数据是否存在;因此您需要检查并基于此发出警报;并且您可以在捕获中使用警报来显示错误消息。因此该代码段将如下所示:
try
{
//Fill the Dataset here
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", "alert('No record with that last name found!')", true);
}
}
catch (Exception )
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", "alert('Error Occured!')", true);
}
注意:您需要在using块内关闭连接,因为using块会为您解决这一问题。(提供者:Dhaval Patel)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句