C# 如何使用 SqlDataSource 处理异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/705134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:08:33  来源:igfitidea点击:

How to handle exceptions with a SqlDataSource

c#asp.netvb.netdatagridviewsqldatasource

提问by Etienne

I have a SqlDataSource that is supplying data to my GridView. Thats all i am using on my form, thus i have NO code behind at all. But somewhere i need a TRY CATCH block just in case my connection get's lost. What code must i place where?

我有一个 SqlDataSource 正在向我的 GridView 提供数据。这就是我在表单上使用的全部内容,因此我根本没有代码。但是在某处我需要一个 TRY CATCH 块,以防万一我的连接丢失。我必须把什么代码放在哪里?

If i get a error i want my lblMessage Text to be "No connection".

如果出现错误,我希望我的 lblMessage 文本为“无连接”。

Edit

编辑

My GridView in my Machine.aspx

我的 Machine.aspx 中的 GridView

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" 
    Height="209px" PageSize="7" Width="331px" AllowSorting="True" 
                DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="Total" HeaderText="Total" ReadOnly="True" 
            SortExpression="Total" DataFormatString="{0:R#,###,###}" >
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>
        <asp:BoundField DataField="b134_rmcid" HeaderText="Machine"  ReadOnly="True" 
            SortExpression="b134_rmcid" >
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>
        <asp:BoundField DataField="b134_recdate" DataFormatString="{0:d/MM/yyyy}" 
            HeaderText="Date" ReadOnly="True" SortExpression="b134_recdate" >
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>
    </Columns>
</asp:GridView>

My Connection right under my Gridview in my Machine.aspx

我的连接就在我的 Machine.aspx 中的 Gridview 下

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:ODBC_ConnectionString %>" 
    ProviderName="<%$ ConnectionStrings:ODBC_ConnectionString.ProviderName %>" 

    SelectCommand="SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate FROM B134HRE" 
    onselected="SqlDataSource1_Selected">

</asp:SqlDataSource>

My Code in my Code Behind file in my Machine.aspx.cs

我的代码隐藏在我的 Machine.aspx.cs 文件中

protected void Page_Load(object sender, EventArgs e)
{
    lblError.Text = "hello there";
    SqlDataSource1.Selected += new SqlDataSourceStatusEventHandler(SqlDataSource1_Selected);


}


protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{

  if (e.ExceptionHandled)
   {

       lblError.Text = "There is a problem";  

   }

}

And still for some ready when i place a BreakPoint in my Selected Event it does not even get to it???

当我在我的选定事件中放置一个断点时,它甚至没有到达它?

Why?

为什么?

回答by John Saunders

I believe you want to handle the Selected event of the SQLDataSource, and check the event argument for the exception.

我相信您想处理 SQLDataSource 的 Selected 事件,并检查异常的事件参数。

回答by Paul Suart

The SqlDataSource has an Selectedevent. Add a handler to this event like so, and handle any errors (show an informative message etc) in this handler.

SqlDataSource 有一个Selected事件。像这样向此事件添加一个处理程序,并在此处理程序中处理任何错误(显示信息性消息等)。

void GridView1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    if (e.ExceptionHandled)
    {
        //Show error message
    }
}

Sorry, but you're going to have to have some code in the code-behind!

抱歉,您将不得不在代码隐藏中添加一些代码!

Edit

编辑

Looking at your code, I don't think you're ever binding your GridView, so your SqlDataSource is never trying to select the data from your database.

查看您的代码,我认为您从未绑定过您的 GridView,因此您的 SqlDataSource 从未尝试从您的数据库中选择数据。

In your Page_Load method, add the following code:

在您的 Page_Load 方法中,添加以下代码:

    if (!IsPostBack)
    {
        GridView1.DataBind();
    }

Further edit

进一步编辑

Try changing "onselected" to "OnSelected" on your SqlDataSource and remove the line to bind your event handler in the code behind.

尝试在您的 SqlDataSource 上将“onselected”更改为“OnSelected”,并删除该行以在后面的代码中绑定您的事件处理程序。

I'm stumped if that doesn't work as you've basically got the simplest-possible example.

如果这不起作用,我很难过,因为您基本上已经获得了最简单的示例。

Even further edit

进一步编辑

Try this instead

试试这个

void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
    if (e.Exception != null)
    {
        //Show error message
        lblError.Text = "There is a problem"; 

        //Set the exception handled property so it doesn't bubble-up
        e.ExceptionHandled = true;
    }
}

回答by Lachlan Wetherall

Create an event handler for the Selected event of the SqlDataSource, test if an exception occurred, perform whatever error reporting you want, then indicate that you've now handled the error.

为 SqlDataSource 的 Selected 事件创建一个事件处理程序,测试是否发生了异常,执行您想要的任何错误报告,然后表明您现在已经处理了错误。

    mSqlDataSource.Selected += new sqlDataSourceStatusEventHandler(mSqlDataSource_Selected);


    void mSqlDataSource_Selected(object sender, SqlDataSourceStatusEventArgs e)
    {
        if (e.Exception != null)
        {
            mErrorText.Text = e.Exception.Message;
            mErrorText.Visible = true;
            e.ExceptionHandled = true;
        }
    }

回答by Jesse Mwangi

you need to handle the error from code behind of your Gridview_ItemInserting or gridview_itemupdating so as to fire before your code are submitted to the sql control.

您需要处理来自 Gridview_ItemInserting 或 gridview_itemupdating 代码后面的错误,以便在将代码提交给 sql 控件之前触发。

protected void GridView1_ItemInserting(object sender,DetailsViewInsertEventArgs e)
{
if (e.Exception != null)
{
Lblerror.text="error message"
}
}

do so also for updating

这样做也是为了更新

回答by Jesse Mwangi

void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception = null)
{
//bind data to gridview
GridView1.DataBind();
}
else
{
//Show error message    
lblError.Text = "There is a problem";
//Set the exception handled property so it doesn't bubble-up
e.ExceptionHandled = true;
}
}