Link to home
Start Free TrialLog in
Avatar of reedsster1
reedsster1

asked on

How to reset a radiobutton that was created as a literal in a gridview when a selectedindexchange event occurs in a DDL

Hello
I have a run of drop down lists with auto postback enabled that run stored procedures to populate the information into the next drop down list.  The final drop down lists passes the selected information into a gridview which creates a radiobutton within the gridview using the literal control.  
I am having a slight problem.
Once the gridview has been created, if I select a value, then change the DDL that loads the gridview, I get an error:
Line 104:                return -1;
Line 105:            else
Line 106:                return Convert.ToInt32(Request.Form["OptionsGroup"]);
Line 107:        }
Line 108:    }

I assume this is because the radiobutton is trying to remain checked.  How do I clear this gridview?  The C# code behind does not recognize the radiobutton control.  
I have the DDL's clearing each other like so:
 protected void YearDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {

        MakeDropDownList.Items.Clear();
        MakeDropDownList.Items.Insert(0, new ListItem("Select A Make", "0"));
        MakeDropDownList.SelectedValue = "0";
        ModelDropDownList.Items.Clear();
        ModelDropDownList.Items.Insert(0, new ListItem("Select A Model", "0"));
        ModelDropDownList.SelectedValue = "0";
     
       
        PartDropDownList.SelectedValue = "0";


Is it possible to do something similar to this radiobutton?  Here is the code for the gridview:
<td align="left" colspan="3" style="width: 533px; height: 41px" valign="middle">
                         &nbsp;<asp:GridView ID="OptionsGridView" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource5" DataKeyNames="Application" OnRowDataBound="OptionsGridView_RowDataBound" GridLines="None" Width="541px">
                             <Columns>
                                 
                                 ...
                                 <asp:TemplateField HeaderText="Select:">
                                     <ItemTemplate>
                                         &nbsp;<asp:Literal ID="RadioButtonMarkup" runat="server"></asp:Literal>
                                   
                                     </ItemTemplate>
                                 </asp:TemplateField>                                                              
                                                           </Columns>
                         </asp:GridView>
Here is the code behind to create the radiobutton:

private int OptionsSelectedIndex
    {
        get
        {
            if (string.IsNullOrEmpty(Request.Form["OptionsGroup"]))
                return -1;
            else
                return Convert.ToInt32(Request.Form["OptionsGroup"]);
        }
    }


    protected void OptionsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            {
                // Grab a reference to the Literal control
                Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
                // Output the markup except for the "checked" attribute
                output.Text = string.Format("<input type='radio' runat='server' name='OptionsGroup' id='RowSelector{0}' value='{0}'", e.Row.Cells[1].Text);
                // See if we need to add the "checked" attribute
                if (OptionsSelectedIndex == e.Row.RowIndex)
                    output.Text += " checked='checked'";
                // Add the closing tag
                output.Text += " />";
            }
          }

Any help would be appreciated!
Thanks

Avatar of CmdoProg2
CmdoProg2
Flag of United States of America image

Here is the example that used..  I have a seperate class the generates the datatable using a dataset.




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="radioExample.aspx.cs" Inherits="radioExample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Radio Example</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
      <asp:ListItem>Fred</asp:ListItem>
      <asp:ListItem>Alice</asp:ListItem>
      <asp:ListItem>George</asp:ListItem>
    </asp:DropDownList>
    <asp:GridView ID="OptionsGridView" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1" DataKeyNames="FredID"
      GridLines="None" OnRowDataBound="OptionsGridView_RowDataBound" Width="500px">
      <Columns>
        <asp:BoundField DataField="FredID" HeaderText="FredID" InsertVisible="False" ReadOnly="True" SortExpression="FredID" />
        <asp:BoundField DataField="part" HeaderText="part" SortExpression="part" />
        <asp:TemplateField HeaderText="InventoryNbr" SortExpression="InventoryNbr">
          <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%# Eval("InventoryNbr") %>' />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Select:">
          <ItemTemplate>
            &nbsp;<asp:Literal ID="RadioButtonMarkup" runat="server"></asp:Literal>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" Text="Find Option" OnClick="Button1_Click" />
    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="getFred" TypeName="checkDate"></asp:ObjectDataSource>
  </div>
  </form>
</body>
</html>


--------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class radioExample : System.Web.UI.Page
{
  int OptionsSelectedIndex;

  protected void Page_Load(object sender, EventArgs e)
  {
    OptionsSelectedIndex = 5;
    if (IsPostBack)
    {
      int opt = FindOption();
    }
  }

  private int FindOption()
  {
    if (Request.Form["OptionsGroup"] == null)
    { return -1; }
    else
    { return Convert.ToInt32(Request.Form["OptionsGroup"]); }
  }


  protected void OptionsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      {
        // Grab a reference to the Literal control
        Literal output = (Literal)e.Row.FindControl("RadioButtonMarkup");
        // Output the markup except for the "checked" attribute
        output.Text = string.Format("<input type='radio' name='OptionsGroup' id='RowSelector{0}' value='{1}'", e.Row.Cells[1].Text, e.Row.Cells[0].Text);
        // See if we need to add the "checked" attribute
        if (OptionsSelectedIndex == e.Row.RowIndex)
          output.Text += " checked='checked'";
        // Add the closing tag
        output.Text += " />";
      }
    }
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    string opt = Request.Form["OptionsGroup"];
  }

  protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
  {
    Literal output;
    String inputHTML;
    foreach (GridViewRow gvr in OptionsGridView.Rows)
    {
      output = (Literal)gvr.FindControl("RadioButtonMarkup");
      inputHTML = output.Text.Replace(" checked='checked'", "");
      output.Text = inputHTML;
    }
  }


}

Open in new window

Avatar of reedsster1
reedsster1

ASKER

Changed things around to be more in line with your code.  Still getting an error:

Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:


Line 51:         { return -1; }
Line 52:         else
Line 53:         { return Convert.ToInt32(Request.Form["OptionsGroup"]); }
Line 54:     }
Line 55:
 

Check your data to ensure the value of the input radio control is an Int32.  Your InventoryNbr field may contain non-numeric characters such as 32-32345, 2345H349 or larger value than 32 bits.
 A sledgehammer test to isolate the problem would to replace line 53 with the snippet below, but a try..catch would be preferred for operations:
{
  string optionsGroup = Request.Form["OptionsGroup"]
  return Convert.ToInt32(optionsGroup);
 }
It does.  InventoryNbr is a varchar and contains alpha numeric's.  Does that change how I should have any of this formatted?
ASKER CERTIFIED SOLUTION
Avatar of CmdoProg2
CmdoProg2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awesome!  I'm one step closer to my site being live!
That worked like a charm.  The only problem I have with this function still is that the radio button remains checked even when the values change.  I should be able to figure that one out on my own though.  Thanks!
Scott
Actually, still having a bit of trouble.  The value getting pulled into the varible I am trying to pass onto the next page (InventoryNbr) is now just the row number (0,1,2,3,4 ETC)
I am getting it via:

string INVNUM = Request.Form["OptionsGroup"];

Any idea?
Ok, I see that you covered that in your answer, I shouldn't have been so quick to act here.  How can I get it to return InventoryNbr still in my

string INVNUM = Request.Form["OptionsGroup"];

and still get the gridview to reset when the prior DDL is changed without the error?
I've posted a related question with updated and consolidated information.
https://www.experts-exchange.com/Programming/Languages/.NET/newQuestionWizardRelated.jsp?qid=25195209
Nevermind, I was able to get it to work as I intended by removing the optionsselectedindex event completely and putting:

OptionsGridView.DataSource = null;
        OptionsGridView.DataBind();
to the selectedindexchanged event for the DDL that creates the gridview, it solves all my problems.  Thanks again for your input.