gpt4 book ai didi

c# - 如何使用 SqlDataSource 处理异常

转载 作者:行者123 更新时间:2023-12-02 08:52:10 27 4
gpt4 key购买 nike

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

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

编辑

我的 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>

我的连接就在我的 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>

我的代码在我的 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";

}

}

仍然有一些准备好,当我在选定的事件中放置断点时,它甚至没有到达它???

为什么?

最佳答案

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

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

抱歉,但是您必须在代码隐藏中添加一些代码!

编辑

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

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

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

进一步编辑

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

如果这不起作用,我会很困惑,因为你基本上已经得到了最简单的示例。

进一步编辑

试试这个

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;
}
}

关于c# - 如何使用 SqlDataSource 处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/705134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com