Eti*_*nne 4 c# vb.net asp.net datagridview sqldatasource
我有一个SqlDataSource,它向我的GridView提供数据.多数民众赞成我在我的表格上使用,因此我根本没有任何代码.但在某些地方我需要一个TRY CATCH块以防万一我的连接丢失了.我必须在哪里放置什么代码?
如果我收到错误,我希望我的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>
Run Code Online (Sandbox Code Playgroud)
我的连接就在我的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>
Run Code Online (Sandbox Code Playgroud)
我的Code.aspx.cs中的Code Behind文件中的代码
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";
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些准备好的时候,我在我的选定事件中放置一个BreakPoint,它甚至没有得到它?
为什么?
SqlDataSource有一个Selected
事件.像这样为此事件添加一个处理程序,并处理此处理程序中的任何错误(显示信息性消息等).
void GridView1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.ExceptionHandled)
{
//Show error message
}
}
Run Code Online (Sandbox Code Playgroud)
抱歉,您将不得不在代码隐藏中使用一些代码!
编辑
查看您的代码,我认为您不会绑定GridView,因此您的SqlDataSource永远不会尝试从您的数据库中选择数据.
在Page_Load方法中,添加以下代码:
if (!IsPostBack)
{
GridView1.DataBind();
}
Run Code Online (Sandbox Code Playgroud)
进一步编辑
尝试在SqlDataSource上将"onselected"更改为"OnSelected"并删除该行以在后面的代码中绑定您的事件处理程序.
如果这不起作用我很难过,因为你基本上得到了最简单的例子.
甚至进一步编辑
试试这个
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;
}
}
Run Code Online (Sandbox Code Playgroud)