How to get cell value from gridview when radio button list item is selected?

≯℡__Kan透↙ 提交于 2020-01-17 00:37:27

问题


I have a gridview which is displaying data dynamically from SQL table. No problem with this part. I've added a colunm that contains a radio button list. I would like to get all cells value of Column 3 (index 2) if a radio button list item of these rows is selected when the user click on the Submit button.

My gridview :

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

Edit : Gridview example

---------------------------------------------
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       |
--------------------------------------------

If a radio list item is selected, i would like to get value of the corresponding cell in column1 when clicking on submit button.

My code behind :

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

The error faced when submitting :

[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 know how to handle this.


回答1:


To expand on the answer (and my comment) given by "Selva TS"

You have two issues, as Selva pointed out you should be validating that the RadioButtonList Selected item is not null before using it. Doing so will stop your error but will still not resolve the issue, the issue that you have is that the Page_Load is firing and re-binding your grid view which has the effect of resetting your radio button list.

To get around this change your Page_Load to

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

This will only bind the gridview if it is on the first load of the page (or it it is refreshed) not if one of the controls causes a postback.

You then need to amend the submit click as shown by 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();
          }
      }
    }
 }

Doing JUST the page_load change will likely resolve the issue itself - but really you should be checking the SelectedItem for null just in case anyway! - Users can be fools and you should always try to anticipate their foolishness!




回答2:


The problem is if you are not selected any RadioButton, the SelectedItem is always null. Just add one more validation in RadioButton control whether SelectedItem is null or not.

Adding if (rb.SelectedItem != null) condition in your code before validating SelectedItem will work,

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

Also, as d3vy suggested, adding if (!Page.IsPostBack) in Page_Load will stop wiping the SelectedItem in the 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();
   }
}



回答3:


Had almost a similar problem, used input instead of asp:radiobutton:

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

Then on buttonClick use request.form to get the value of selected radiobutton. If not selected it would return null.

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

Here is the link for more info:http://www.codeproject.com/Articles/13050/RadioButtons-inside-a-GridView-control



来源:https://stackoverflow.com/questions/28875542/how-to-get-cell-value-from-gridview-when-radio-button-list-item-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!