【问题标题】:How to get cell value from gridview when radio button list item is selected?选择单选按钮列表项时如何从gridview获取单元格值?
【发布时间】:2015-03-05 10:26:54
【问题描述】:

我有一个网格视图,它从 SQL 表中动态显示数据。这部分没有问题。我添加了一个包含单选按钮列表的列。如果在用户单击“提交”按钮时选择了这些行的单选按钮列表项,我想获取第 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

不知道如何处理。

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

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

    您有两个问题,正如 Selva 指出的那样,您应该在使用 RadioButtonList Selected 项目之前验证它不为空。这样做将停止您的错误,但仍无法解决问题,您遇到的问题是 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,而不是在某个控件导致回发时绑定。

    然后你需要修改提交点击,如 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();
              }
          }
        }
     }
    

    仅更改 page_load 可能会解决问题本身 - 但实际上您应该检查 SelectedItem 是否为空,以防万一! - 用户可能是傻瓜,您应该始终尝试预测他们的愚蠢!

    【讨论】:

      【解决方案2】:

      问题是如果您没有选择任何RadioButtonSelectedItem 始终是null。只需在RadioButton 中再添加一个验证,即可控制SelectedItem 是否为null

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

      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 建议的那样,在Page_Load 中添加if (!Page.IsPostBack) 将停止擦除RadioButtonList 中的SelectedItem

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

      【讨论】:

      • 你是对的,但是这里还有第二个问题 - 页面加载时发生了 gridview 绑定,并将擦除 RadioButton 列表的 selectedItem 属性。除了上面你应该有 if (!isPostBack) { //Your binding code here } 否则当页面加载被点击时,你将从单选按钮列表中丢失 selectedItem。希望这是有道理的 - 我使用 Web 表单已经有一段时间了,但多次被同一个问题绊倒!
      • @D3vy 这也是可能的情况。
      • 我已经添加了你的两个建议,但仍然遇到同样的错误
      • RadioButtonList rb = (RadioButtonList)row.FindControl("Radio1");添加断点rb的值是多少?它是 null 还是设法找到了控件?
      • @Shnabr 你想用这个字符串得到什么 id = row.Cells[2].Text;? GridView 中没有 Cells[2]。请检查那部分。
      【解决方案3】:

      几乎有类似的问题,使用输入而不是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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多