如何在此Asp.Net代码中使用异常处理 [英] How Do I Use Exceptional Handling In This Asp.Net Code
问题描述
protected void Button5_Click(object sender,EventArgs e)
{
SqlConnection con = new SqlConnection(con_str);
SqlDataAdapter ad1;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter(select * from table1 ,con);
ad1.Fill(ds,0);
GridView2.DataSource = ds.Tables [0];
GridView2.DataBind();
}
将代码保存在try catch块中。
你可以这样做:
SqlConnection con = null;
if(con == null || con.State!= ConnectionState.Open)
{
con = new SqlConnection(你的连接字符串);
}
尝试
{
con.Open();
SqlDataAdapter ad1;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter(select * from Table1,con);
ad1.Fill(ds,0);
GridView2.DataSource = ds.Tables [ 0];
GridView2.DataBind();
}
catch(例外)
{
throw;
}
终于
{
con.Close();
}
protected void Button4_Click(object sender,EventArgs e)
{
SqlConnection con = null;
if (con == null || con.State!= ConnectionState.Open)
{
con = new SqlConnection(con_str);
}
尝试
{
con.Open();
SqlDataAdapter ad1 ;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter(select * from table,con);
ad1。填充(ds,0);
GridView1.Da taSource = ds.Tables [0];
GridView1.DataBind();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
protected void Button5_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(con_str);
SqlDataAdapter ad1;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter("select * from table1", con);
ad1.Fill(ds, "0");
GridView2.DataSource = ds.Tables["0"];
GridView2.DataBind();
}
Keep your code inside try catch block.
You can do like this:
SqlConnection con=null;
if (con == null || con.State != ConnectionState.Open)
{
con = new SqlConnection("Your connection string");
}
try
{
con.Open();
SqlDataAdapter ad1;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter("select * from Table1", con);
ad1.Fill(ds, "0");
GridView2.DataSource = ds.Tables["0"];
GridView2.DataBind();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection con = null;
if (con == null || con.State != ConnectionState.Open)
{
con = new SqlConnection(con_str);
}
try
{
con.Open();
SqlDataAdapter ad1;
DataSet ds = new DataSet();
ad1 = new SqlDataAdapter("select * from table", con);
ad1.Fill(ds, "0");
GridView1.DataSource = ds.Tables["0"];
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
这篇关于如何在此Asp.Net代码中使用异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!