如何在选择单选按钮列表项时从gridview获取单元格值?

时间:2015-03-05 10:26:55

标签: c# asp.net gridview

我有一个gridview,它从SQL表中动态显示数据。这部分没问题。我添加了一个包含单选按钮列表的colunm。如果在用户单击“提交”按钮时选择了这些行的单选按钮列表项,我想获取第3列(索引2)的所有单元格值。

我的网格视图:

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
    <HeaderTemplate>
        RadioButtonList
    </HeaderTemplate>
    <ItemTemplate>
        <asp:RadioButtonList ID="Radio1" runat="server">
            <asp:ListItem Value="1" Text="OK" />
            <asp:ListItem Value="0" Text="KO" />
        </asp:RadioButtonList>
    </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click"/>

protected void Page_Load(object sender, EventArgs e)
{
    string strSQLconnection = "Connection to DB";
    SqlConnection sqlConnection = new SqlConnection(strSQLconnection);

    SqlCommand sqlCommand = new SqlCommand("SELECT Champ1, Champ2, Camp3 FROM Table1 WHERE Condition1 IS NULL AND Condition2 IS NULL", sqlConnection);

    sqlConnection.Open();

    SqlDataReader reader = sqlCommand.ExecuteReader();

    GridView1.DataSource = reader;
    GridView1.DataBind();

    sqlConnection.Close();
}

编辑:Gridview示例

---------------------------------------------
Radio   | Column0   | Column1   | Column2   |
---------------------------------------------
°OK °KO | abc       | abc       | abc       |
---------------------------------------------
°OK °KO | abc       | abc       | abc       |
--------------------------------------------- 
°OK °KO | abc       | abc       | abc       |
--------------------------------------------- 
°OK °KO | abc       | abc       | abc       |
--------------------------------------------- 
°OK °KO | abc       | abc       | abc       |
--------------------------------------------- 
°OK °KO | abc       | abc       | abc       |
--------------------------------------------

如果选择了一个单选项列表项,我想在单击提交按钮时获取column1中相应单元格的值。

我的代码背后:

protected void Submit_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
    //Find the Radio button control
    RadioButtonList rb = (RadioButtonList)row.FindControl("Radio1");

    if (rb.SelectedItem.Text == "OK")
    {

        string id = row.Cells[2].Text;

        string query = "Query";

        SqlConnection con = new SqlConnection("Connection to DB");
        SqlCommand cmd = new SqlCommand(query, con);

        con.Open();
        added = cmd.ExecuteNonQuery();

        con.Close();
    }
}
}

提交时遇到的错误:

[NullReferenceException: Object reference not set to an instance of an object.]
   MasterPage.Submit_Click(Object sender, EventArgs e) +202
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +114
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +139
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +28
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2980

Dot知道如何处理这个问题。

3 个答案:

答案 0 :(得分:1)

扩展“Selva TS”给出的答案(以及我的评论)

您有两个问题,因为Selva指出您应该在使用之前验证RadioButtonList Selected项是否为null。这样做会停止您的错误,但仍然无法解决问题,您遇到的问题是Page_Load正在触发并重新绑定您的网格视图,这会重置您的单选按钮列表。

要解决此问题,请将Page_Load更改为

protected void Page_Load(object sender, EventArgs e)
{
     if (!isPostBack)
     {
        string strSQLconnection = "Connection to DB";
        SqlConnection sqlConnection = new SqlConnection(strSQLconnection);

        SqlCommand sqlCommand = new SqlCommand("Query", sqlConnection);

        sqlConnection.Open();

        SqlDataReader reader = sqlCommand.ExecuteReader();

        GridView1.DataSource = reader;
        GridView1.DataBind();

        sqlConnection.Close();
    }
}

如果gridview位于页面的第一次加载(或刷新它),它将仅绑定gridview,而不是其中一个控件导致回发。

然后,您需要修改提交点击,如Selva所示

protected void Submit_Click(object sender, EventArgs e)
{
 foreach (GridViewRow row in GridView1.Rows)
  {
    //Find the Radio button control
      RadioButtonList rb = (RadioButtonList)row.FindControl("Radio1");
      if (rb.SelectedItem != null)
      {
          if (rb.SelectedItem.Text == "OK")
           {
              string id = row.Cells[2].Text;
              string query = "Query";

              SqlConnection con = new SqlConnection("Connection to DB");
              SqlCommand cmd = new SqlCommand(query, con);

              con.Open();
              added = cmd.ExecuteNonQuery();

              con.Close();
          }
      }
    }
 }

执行JUST page_load更改可能会解决问题本身 - 但实际上你应该检查SelectedItem是否为null,以防万一! - 用户可能是傻瓜,你应该总是试着预测他们的愚蠢!

答案 1 :(得分:0)

问题是,如果您未选择任何RadioButton,则SelectedItem始终为null。只需在RadioButton控件中再添加一个验证,SelectedItem是否为null

在验证if (rb.SelectedItem != null)之前,在代码中添加SelectedItem条件将起作用,

protected void Submit_Click(object sender, EventArgs e)
 {
     foreach (GridViewRow row in GridView1.Rows)
      {
        //Find the Radio button control
          RadioButtonList rb = (RadioButtonList)row.FindControl("Radio1");
          if (rb.SelectedItem != null)
          {
              if (rb.SelectedItem.Text == "OK")
               {
                  string id = row.Cells[2].Text;
                  string query = "Query";

                  SqlConnection con = new SqlConnection("Connection to DB");
                  SqlCommand cmd = new SqlCommand(query, con);

                  con.Open();
                  added = cmd.ExecuteNonQuery();

                  con.Close();
              }
          }
      }
   }

此外,正如d3vy建议的那样,在if (!Page.IsPostBack)中添加Page_Load将停止擦除SelectedItem中的RadioButtonList

protected void Page_Load(object sender, EventArgs e)
{
 if (!Page.IsPostBack)
   {
      string strSQLconnection = "Connection to DB";
      SqlConnection sqlConnection = new SqlConnection(strSQLconnection);

      SqlCommand sqlCommand = new SqlCommand("Query", sqlConnection);

      sqlConnection.Open();

      SqlDataReader reader = sqlCommand.ExecuteReader();

      GridView1.DataSource = reader;
      GridView1.DataBind();

      sqlConnection.Close();
   }
}

答案 2 :(得分:0)

几乎有类似问题,使用输入而不是asp:radiobutton

<asp:TemplateField HeaderText="Select One">
    <ItemTemplate>
      <input name="MyRadioButton" type="radio" 
                value='<%# Eval("CategoryID") %>' />
    </ItemTemplate>
</asp:TemplateField>

然后在buttonClick上使用request.form获取所选radiobutton的值。如果未选中,则返回null。

protected void Button1_Click(object sender, EventArgs e)
{
  string selectedValue = Request.Form["MyRadioButton"];
  lblMsg.Text = selectedValue;
}

以下是更多信息的链接:http://www.codeproject.com/Articles/13050/RadioButtons-inside-a-GridView-control