如何使用try和catch处理Selected IndexOutOfRange?

时间:2013-05-03 11:45:06

标签: asp.net visual-studio-2010 gridview exception-handling datagridview

我在 Asp.net 中有一个gridview和一个删除按钮。删除仅在从gridview中选择行时才有效。我想通过使网站更加用户友好来防止网站崩溃。因此,如果用户未选择行并按删除,则会通过标签通知他们。是 SelectedVlue 还是 SelectedRow

这就是我的尝试:

if (GridView1.SelectedValue == null)
        {

            int i = GridView1.SelectedIndex;
            myDataSet.Tables["Records"].Rows[i].Delete();

            GridView1.DataSource = myDataSet;
            GridView1.DataBind();
        }
        else
        {
            Label5.Text = "Oops, please select a row";
        }

3 个答案:

答案 0 :(得分:0)

如果未选择任何行,则SelectedRownull。您也可以使用SelectedIndex != -1。但是你正在检查== null而不是!= null,无论如何错误的逻辑。

if (GridView1.SelectedRow != null)
{
    // ...
}
else
{
    Label5.Text = "Oops, please select a row";
}

if (GridView1.SelectedIndex != -1)
{
    // ...
}
else
{
    Label5.Text = "Oops, please select a row";
}

答案 1 :(得分:0)

您应该用以下代码替换您的代码:

        if (GridView1.SelectedRow != null && GridView1.SelectedIndex != -1)
        {
            int i = GridView1.SelectedIndex;
            myDataSet.Tables["Records"].Rows[i].Delete();

            GridView1.DataSource = myDataSet;
            GridView1.DataBind();
        }
        else
        {
            Label5.Text = "Oops, please select a row";
        }

答案 2 :(得分:0)

试试这个:

if(GridView.SelectedRow != null)
{
    // proceed with your action
}
else
{    
    Label5.Text = "Oops, please select a row";
}