单击按钮时System.ArgumentOutOfRangeException

时间:2018-06-19 21:43:03

标签: asp.net webforms

我在button中使用了gridview字段。当我按下索引大于5的按钮时,收到此异常:

  

System.ArgumentOutOfRangeException:'索引超出范围。一定是   非负数且小于集合的大小。'

public partial class WebForm2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "btn")
        {
            int crow;
            crow = Convert.ToInt32(e.CommandArgument.ToString());
            string v = GridView1.Rows[crow].Cells[1].Text;
            int a = Int32.Parse(v);
            string b = "true";
            SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
            con.Open();
            SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='"+b+"' WHERE Id ='"+ a+"'", con);
            cmd.ExecuteNonQuery();
            con.Close();
            v = "";

        }
    }
}

Page Layout

1 个答案:

答案 0 :(得分:0)

公共局部类WebForm2:System.Web.UI.Page     {         受保护的void Page_Load(对象发送者,EventArgs e)         {             GridView1.DataSource = SqlDataSource1;             GridView1.DataBind();         }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "btn")
        {
            int crow;
            crow = Convert.ToInt32(e.CommandArgument.ToString());
            try
            {
                string v = GridView1.Rows[crow].Cells[1].Text;

                Application["id"] = v;
                v = "";
            }
            catch (ArgumentOutOfRangeException)
            {

            }
            finally
            {
               string a = Application["id"].ToString();
                Label1.Text = a.ToString();


                string b = "true";
                SqlConnection con = new SqlConnection("Data Source=DESKTOP-LITEG8T;Initial Catalog=UserDb;Integrated Security=True");
                con.Open();
                SqlCommand cmd = new SqlCommand("UPDATE Table_1 SET Status ='" + b + "' WHERE Id ='" + a + "'", con);
                cmd.ExecuteNonQuery();
                con.Close();
                Application["id"] = "";
                a = "";
            }




            }
    }

    }