Category Archives: RadioButtonList

[RESOLVED] Dropdownlist not keeping the selected value after submit

I'm a newbie. So, Please accomodate  if I am asking for some little thing.

In my form, I've many input elements one of which is, a radio button group with Autopostback set to true. After selecting one item from the radio button, the drop down list below fetches values from database and is refreshed. I choose some value in the dropdown list and submit the form. I've many server side validation controls. When I submit the form, if any of the server validation fails, it'll show the error message in the form. But the value I choose in the dropdown list disappears and it shows the first value of the dropdown list.

How to show the selected value in the list after submission of form?

Below is the partial code from my form. When I type anything other than "Hello" is the "Comments" text box, it will show the error message. I know I can use, other validators to check this. But purposely I want to use Customvalidator.

Any help is appreciated. Thks for your time

 

My C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Text;
using System.IO;




public partial class Mytest : System.Web.UI.Page
{




    protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            Populate1();


        }


        Populate2();




    }




    public void Populate1()
    {
        SqlConnection conn1 = new SqlConnection();
        conn1.ConnectionString = ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
        conn1.Open();
        string query = "SELECT * FROM SuggKeyCat";
        SqlCommand cmd = new SqlCommand(query, conn1);


        SqlDataReader ddlValues;
        ddlValues = cmd.ExecuteReader();
        CatList.DataSource = ddlValues;
        CatList.DataValueField = "KeyCat_ID";
        CatList.DataTextField = "KeyCat_Desc";
        CatList.DataBind();


        cmd.Connection.Close();
        cmd.Connection.Dispose();


    }




    public void Populate2()
    {


        BenList.Items.Clear();


        SqlConnection conn2 = new SqlConnection();
        conn2.ConnectionString = ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
        conn2.Open();
        string query2 = "SELECT * FROM SuggCat where SCate = '" + CatList.Text.Trim() + "' order by Cat_ID";
        SqlCommand cmd2 = new SqlCommand(query2, conn2);


        SqlDataReader ddlValues2;
        ddlValues2 = cmd2.ExecuteReader();
        BenList.DataSource = ddlValues2;
        BenList.DataValueField = "Cat_ID";
        BenList.DataTextField = "Cat_Desc";
        BenList.DataBind();
        cmd2.Connection.Close();
        cmd2.Connection.Dispose();


    }




    protected void ValidateServerSide1(object source, ServerValidateEventArgs args)
    {


        if (UrComments.Text != "hello" )
        { args.IsValid = false;}
        else
        { args.IsValid = true; }
    }




    



    protected void DataProcess(object sender, EventArgs e)
    {


        if (Page.IsValid)
        {
            //do something


        }


    }


}



 

My ASP.net code

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

<!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 id="Head1" runat="server">
    <title></title>
    <link rel="Stylesheet" href="style.css" type="text/css" />
</head>
<body>

    <form id="SuggForm" runat="server">    
    <asp:Table ID="Table1" runat="server" BorderColor="#8B8B8B" BorderStyle="solid"  BorderWidth="1px" cellSpacing="10" CellPadding="4" Width="50%"> 
      
    
        <asp:TableRow ID="TableRow8" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell15" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label13" runat="server" Text="Category 1:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
            </asp:TableCell>    
            <asp:TableCell ID="TableCell16" Width="79%" runat="server" VerticalAlign="top">        
                <asp:RadioButtonList AutoPostBack="true" RepeatLayout="Table" RepeatColumns="3" BorderColor="#CFCFCF" CellSpacing="2" CellPadding="2" BorderWidth="1px" BorderStyle="Ridge" Width="50%" Font-Names="verdana" Font-Size="11.5px" ForeColor="#575757"  ID="CatList" runat="server"></asp:RadioButtonList>
           </asp:TableCell>
        </asp:TableRow>
    
    
        <asp:TableRow ID="TableRow12" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell29" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label19" runat="server" Text="Category 2:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
            </asp:TableCell>    
            <asp:TableCell ID="TableCell58" Width="79%" runat="server" VerticalAlign="Top">        
                 <asp:DropDownList BackColor="#ffffff" Font-Names="verdana" Font-Size="0.7em" ForeColor="#575757" ID="BenList" runat="server" Width="100%" Height="40px">
                 </asp:DropDownList>
            </asp:TableCell>
        </asp:TableRow>   
    
    
        <asp:TableRow ID="TableRow2" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ID="TableCell3" Width="20%" runat="server" VerticalAlign="Top">
                <asp:Label ID="Label3" runat="server" Text="Comments:" Font-Names="Verdana" ForeColor="#575757" Font-Size="0.7em" Font-Bold="True"></asp:Label> 
                <asp:TextBox TextMode="MultiLine" BackColor="#ffffff" ID="UrComments" Font-Names="verdana" Font-Size="0.7em" ForeColor="#575757" Rows="5" Width="100%" runat="server"></asp:TextBox>
                <asp:CustomValidator id="CustomValidator1" runat="server" OnServerValidate="ValidateServerSide1" ControlToValidate="UrComments" ErrorMessage="Explanation required."  Font-Names="Verdana" ForeColor="#FF3300" Font-Size="0.7em" Font-Bold="False"></asp:CustomValidator>
            </asp:TableCell>  
        </asp:TableRow>
              
       
        <asp:TableRow ID="TableRow10" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
            <asp:TableCell ColumnSpan="3" HorizontalAlign="right" ID="TableCell19" Width="30%" runat="server" VerticalAlign="Top">
              <asp:ImageButton AlternateText="Submit" ID="SubImg" runat="server" ImageUrl="images/Sub.jpg" OnClick="DataProcess" /> 
          </asp:TableCell>  
        </asp:TableRow>        
        </asp:Table>
        
    </form>  
    
</body>
</html>


 

You have to include populate2 in if (!IsPostBack) as well with the populate1.

That is your Page_Load event will look like

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Populate1();
            Populate2();
        }
    }



Thanks for your reply.

If I do this, When the page is loaded for first time, the dropdown list is empty. 

Also, when I choose some option from radiobutton, again the dropdown list is empty. 

You can simply store the selected value in a session variable and again  set the value selected tot he dropdown  on pageload checking for the PagePostback.

Sorry, Can you elaborate a bit? At what point I need to create  the session variable and how to make it as a selected item when the page is submitted? Thanks

This is not possible using the code you have shown.

Is this ALL code you are having for this page? Is there any other place where you are binding the Dropdownlist?

There is no other place I am binding the dropdownlists.

Ofcourse, I've some more code, but on the "DataProcess" section after the form is successfully submitted, like sending email, updating database etc which is not relevant here.

When I enable and see the traces, I could see under "Form Collection" data - For example, Catlist =1 and Benlist = 3, if I choose item 1 in the radio button and item 3 in the dropdown list. This happens after I click Submit button.

But I suspect that when the page is reloaded after form submission, the dropdown list goes back to default.

Thanks all for your time.

Any one have any idea?

Hi,

invoke method Populate2(); on CatList SelectedIndexChanged event..

 

Regards..

are you sure that you have set AutopostBack property of dropdownlist to true ?

When I add OnSelectedIndexChanged="Populate2();" to the Catlist, I go this error Compiler Error Message: CS1026: ) expected Source Error: Line 19: </asp:TableCell> Line 20: <asp:TableCell ID="TableCell16" Width="79%" runat="server" VerticalAlign="top"> Line 21: <asp:RadioButtonList AutoPostBack="true" RepeatLayout="Table" RepeatColumns="3" BorderColor="#CFCFCF" CellSpacing="2" CellPadding="2" BorderWidth="1px" BorderStyle="Ridge" Width="50%" Font-Names="verdana" Font-Size="11.5px" ForeColor="#575757" ID="CatList" runat="server" OnSelectedIndexChanged="Populate2();"> Line 22: </asp:RadioButtonList> Line 23: </asp:TableCell>

When I add  AutoPostBack="true"  to dropdown list, which method I need to evoke? If there are 2 auto post back, how do I differentiate?

 

Thanks

 

OnSelectedIndexChanged="Populate2"

no ()....the previous posters suggestion was good....you can bind the DDL in RBL selectedIndexChanged event....

Thanks.

I'm sorry.

Couldn't get your point. Since I've posted my code, can you explain a bit more?

Thanks.

 

Hi,

 

  If you want to populate the dropdown value only when changing the radiobuttonlist value, then you can do the following things

 

      Delete the Populate2() from the page load. Then add a SelectedIndexChanged function for the radiobuttonlist. Populate the dropdown value in that function, ie call the function Populate2().

 

Mahesh 

Hi maybe you need to Hold the selected value of dropdownlist in postback before you populate them.  After you populate them set the selected index = to you ddl value

 

Modifie code like this

 

 

public partial class points : System.Web.UI.Page
    {
     private int selectedIndex;

        protected void Page_Load(object sender, EventArgs e)
        {
            SetMyDropDownSelectedIndex();
            Populate1();
            CatList.SelectedIndex = selectedIndex;
            Populate2();
         
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Do post back
        }
        private void SetMyDropDownSelectedIndex()
        {

           DropDownList ddl = Page.FindControl("CatList") as DropDownList;

            y = Convert.ToInt32(ddl.SelectedValue);


           


        }
    }

 

 

 

 

Thanks for your time.

But your code doesn't help to solve my problem.

By the way, your code is truncated in the forum, don't knwo why.

But I got your code in my mailbox and used that. There were some errors in your code (Like the method name not correctly used, what is"y", Catlist instead of Benlist). But I corrected those and run. But not my expected result.

Any other expert opinions?

 

Have you correted this line

y = Convert.ToInt32(ddl.SelectedValue);

to this

selectedIndex = Convert.ToInt32(ddl.SelectedValue);


Or try this

 protected void DataProcess(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            //do something

        }
else{
Populate1();
Populate2();
ddl.SelectedIndex = selectedIndex;
}

    }

Here i have tested this code and it works to keep the dropdown selected Stateafter each postback

 

 

private int selectedIndex;

        protected void Page_Load(object sender, EventArgs e)
        {

            GetIndex();

            if (!IsPostBack)
            {
                Populate1();

            }

            Populate2();



            BenList.SelectedIndex = selectedIndex;


        }
        public void Populate1()
        {
           

        }


        private void GetIndex()
        {
            

            selectedIndex = BenList.SelectedIndex;

        }


        public void Populate2()

        {
            BenList.Items.Clear();
            //This is just to Populate the  Dropdown
            string [] ddlval = {"Swiming","Cricket","Rugby","Football"};


            for (int x = 0; x < ddlval.Length; x++)
            {

                BenList.Items.Add(ddlval[x].ToString());
            }
         

        }

 

Hi,

Add the following code as function and Call where ever u r losing

string selectedValue = HiddenFieldVar.Value;
        BenList.SelectedIndex = 0;
        for (int i = 0; i < BenList.Items.Count; i++)
        {
            if (BenList.Items[i].Value == "selectedvalue")
            {
                BenList.SelectedIndex = i;
            }
        }

 

Thanks

Sree

Mark it as Answer if it helps. So that Others Can not waste their time

use the viewstate property in drop down selected index for both the drop down.

private int selectedIndex;
 
        protected void Page_Load(object sender, EventArgs e)
        {
 
            GetIndex();
 
            if (!IsPostBack)
            {
                Populate1();
 
            }
 
            Populate2();
 
 
 
            BenList.SelectedIndex = selectedIndex;
 
 
        }
        public void Populate1()
        {
            
 
        }
 
 
        private void GetIndex()
        {
             
 
            selectedIndex = BenList.SelectedIndex;
 
        }
 
 
        public void Populate2()
 
        {
            BenList.Items.Clear();
            //This is just to Populate the  Dropdown
            string [] ddlval = {"Swiming","Cricket","Rugby","Football"};
 
 
            for (int x = 0; x < ddlval.Length; x++)
            {
 
                BenList.Items.Add(ddlval[x].ToString());
            }
          
 
        }

magic mushroom,

Big thanks for solving the problem.

It works now.

 

 

 

Im Glad it worked for you

[RESOLVED] Getting value from radiobutton for MailMessage

I'm trying to get a value from a series of radiobuttons to be recognized by the Mail.Body method of system.net.mail MailMessage:

private void btnSend_Click(object sender, System.EventArgs e)

{                                                
MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("myhost-mail.myhost.net");
                mail.From = new MailAddress(chumley@chum.com);
                mail.To.Add(my@chum.com);
                mail.Subject = "This is the Subject";
 mail.IsBodyHtml = true;
 mail.Body = "INFO SUBMITTED FROM: " +  email.Text + "<br>" + firstname.Text  +
 "&nbsp;" +  surname.Text + "<br>" + usertype.SelectedItem.Value  + "<br>" + uname.Text;
    lblStatus.Text = "Sending...";
       SmtpServer.Send(mail);                                                

}
radiobutton code on interface:

Contractor:<asp:radiobutton AutoPostBack="false" GroupName="usertype" Checked="false" ID="contractor" Value="contractor" runat="server" />
        Supplier:<asp:radiobutton AutoPostBack="false" GroupName="usertype"  Checked="false" ID="supplier" Value="supplier" runat="server" />
      Both:<asp:radiobutton AutoPostBack="false" GroupName="usertype"  Checked="false" ID="both" Value="both" runat="server" />

Compiler Error Message: CS0103: The name 'usertype' does not exist in the current context

thanks
chumley

Try using a RadioButtonList as opposed to single RadioButtons

<asp:RadioButtonList ID="userType" runat="server">
            <asp:ListItem Value="Contractor">Contractor</asp:ListItem>
            <asp:ListItem Value="Supplier">Supplier</asp:ListItem>
            <asp:ListItem Value="Both">Both</asp:ListItem>
        </asp:RadioButtonList>
That will allow you to access the value of the selectedItem like you were trying.

[RESOLVED] Gwtting values from dynamic fields

Hello, anyone know of anyway to get the value of this dynamic data? I've been very stress trying to get the value of this fields. but I dont know how should I code upon the submit button to get the dynamic value, I'm doing a 3 tier, with dataset XSD, using can anyone advise me what to do?

By the way, its a button to generate the dynamic fields, and each dynamic fields id is "dynamic field name" + i, so please kindly go through the codes and give me a solution~ its urgent! thanks in advance!

Its quite long though :x

protected void btnGen_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < Convert.ToInt32(tbNum.Text); i++)
        {

            // label and textbox needed
            Label lblSch = new Label();
            TextBox tbSch = new TextBox();
            Label lblWsGrp = new Label();
            DropDownList ddlWsGrp = new DropDownList();
            RadioButtonList rblTra = new RadioButtonList();
            Label lblSTime = new Label();
            Label lblETime = new Label();
            TextBox tbSTime = new TextBox();
            TextBox tbETime = new TextBox();
            Label lblstar = new Label();
            Label space = new Label();
            space.Text = " ";
            Label lbltime = new Label();
            lbltime.Text = "-example format:08:00/13:15-";
            Label lbltime2 = new Label();
            lbltime2.Text = "-example format:08:00/13:15-";
           

            //calendar control for sess date
            AjaxControlToolkit.CalendarExtender CeSess = new AjaxControlToolkit.CalendarExtender();
            CeSess.ID = "SessDate" + i;
            CeSess.Format = "dd/MM/yyyy";
            CeSess.TargetControlID = "tbSch" + i;
            CeSess.TodaysDateFormat = "dd/MM/yyyy";
            CeSess.Enabled = true;
            CeSess.CssClass = "cal_Theme1";
            CeSess.EnableViewState = true;

           //sess date
            lblSch.ID = "lblSch" + i;
            lblSch.Text = "Session Date : ";
            lblSch.EnableViewState = true;

            tbSch.ID = "tbSch" + i;
            tbSch.Width = 210;
            tbSch.Height = 27;
            tbSch.EnableViewState = true;

            //workshop grp
            lblWsGrp.ID = "lblwsgrp" + i;
            lblWsGrp.Text = "Workshop Group : ";
            lblWsGrp.EnableViewState = true;

            ObjectDataSource obddl = new ObjectDataSource();
            obddl.ID = "obddl" + i;
            obddl.TypeName = "BusinessLogic.RegBLL";
            obddl.SelectMethod = "GetAllReg";
            obddl.DataBind();

            ddlWsGrp.ID = "ddlWsGrp" + i;
            ddlWsGrp.Height = 27;
            ddlWsGrp.Width = 210;
            ddlWsGrp.Items.Add("1");
            ddlWsGrp.Items.Add("2");
            //ddlWsGrp.DataSourceID = obddl.ID;
            //ddlWsGrp.AppendDataBoundItems = true;
            //ddlWsGrp.DataTextField.Equals("wsGrp");
           // ddlWsGrp.DataValueField.Equals("regID");
            ddlWsGrp.EnableViewState = true;

            //Start Time
            lblSTime.ID = "ST" + i;
            lblSTime.Text = "Start Time : ";
            lblSTime.EnableViewState = true;

            tbSTime.ID = "strt" + i;
            tbSTime.Width = 210;
            tbSTime.Height = 27;
            tbSTime.EnableViewState = true;

            //End Time
            lblETime.ID = "ET" + i;
            lblETime.Text = "End Time : ";
            lblETime.EnableViewState = true;

            tbETime.ID = "endt" + i;
            tbETime.Width = 210;
            tbETime.Height = 27;
            tbETime.EnableViewState = true;           
           

            //table to store data
            TableRow trow = new TableRow();
            TableRow trow2 = new TableRow();
            TableRow trow3 = new TableRow();
          

            //row1
            TableCell tc1 = new TableCell();
            TableCell tc2 = new TableCell();
            TableCell tc3 = new TableCell();
            TableCell tc4 = new TableCell();
            TableCell tc45 = new TableCell();
            //row2
            TableCell tc25 = new TableCell();
            TableCell tc26 = new TableCell();
            TableCell tc27 = new TableCell();
            TableCell tc28 = new TableCell();
            //row3
            TableCell tc29 = new TableCell();
            TableCell tc30 = new TableCell();
            TableCell tc31 = new TableCell();
            TableCell tc32 = new TableCell();           

            tc1.Controls.Add(lblSch);
            tc2.Controls.Add(tbSch);
            tc3.Controls.Add(lblWsGrp);
            tc4.Controls.Add(ddlWsGrp);
            tc45.Controls.Add(space);

           tc25.Controls.Add(lblSTime);
            tc26.Controls.Add(tbSTime);
            tc27.Controls.Add(lblETime);
            tc28.Controls.Add(tbETime);

            tc29.Controls.Add(space);
            tc30.Controls.Add(lbltime);
            tc31.Controls.Add(space);
            tc32.Controls.Add(lbltime2);

          trow.Cells.Add(tc1);
            trow.Cells.Add(tc2);
            trow.Cells.Add(tc3);
            trow.Cells.Add(tc4);
            trow.Cells.Add(tc45);
             trow2.Cells.Add(tc26);
            trow2.Cells.Add(tc27);
            trow2.Cells.Add(tc28);
            trow3.Cells.Add(tc29);
            trow3.Cells.Add(tc30);
            trow3.Cells.Add(tc31);
            trow3.Cells.Add(tc32);

            this.table3.Rows.Add(trow);
            this.table3.Rows.Add(trow2);
            this.table3.Rows.Add(trow3);
        }
    }

 

 

 

I think you can create a loop on your table rows then a nested loop with the cells , if you're using foreach you wont need the id.

Hi there, thanks for replying,

Do you have an example which i can refer to? thanks :) 

I dont have exact code but it's something like this :

foreach (
TableRow
x in Table1.Rows)
{

     

foreach (
TableCell y 
 in 
TableRow.Cells
)
    {

             foreach(Control ctrl in y .Controls)
              {
               }

       }

    }

}


Hi, am i right to declare it this way? because i need to get the values from 4 fields, namely 3 textboxes and from 1 dropdownlist :), and then to pass it to insert into my database :)

foreach (TableRow row in table3.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Control c in cell.Controls)
                    {
                        for(int r= 0 ; r <cell.Controls.Count; r++)
                        {
                          
                            if(c.GetType() == typeof(TextBox))
                            {
                                if((c.ID.Contains("tbSch")))
                                {
                                    TextBox tbSch = c as TextBox;
                                    string sessDate = tbSch.Text;
                                }
                                else if ((c.ID.Contains("strt")))
                                {
                                    TextBox tbST = c as TextBox;
                                    string sTime = tbST.Text;
                                }
                                else if ((c.ID.Contains("endt")))
                                {
                                    TextBox tbET = c as TextBox;
                                    string sTime = tbET.Text;
                                }
                         
                            }
                            else if (c.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddlWs = c as DropDownList;
                                string wsGrp = ddlWs.SelectedValue.ToString();
                            }
                        }
                    }
                }
            }

foreach (TableRow row in table3.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    foreach (Control c in cell.Controls)
                    {
                            if(c.GetType() == typeof(TextBox))
                            {
                                if((c.ID.Contains("tbSch")))
                                {
                                    TextBox tbSch = c as TextBox;
                                    string sessDate = tbSch.Text;
                                }
                                else if ((c.ID.Contains("strt")))
                                {
                                    TextBox tbST = c as TextBox;
                                    string sTime = tbST.Text;
                                }
                                else if ((c.ID.Contains("endt")))
                                {
                                    TextBox tbET = c as TextBox;
                                    string sTime = tbET.Text;
                                }
                         
                            }
                            else if (c.GetType() == typeof(DropDownList))
                            {
                                DropDownList ddlWs = c as DropDownList;
                                string wsGrp = ddlWs.SelectedValue.ToString();
                            }
                    
                    }
                }
            }


you're having an extra loop you're already looping on controls so no need for the last nested for , else than this I guess you're right .



Hey, thanks for the reply, I tried debugging, but I cannot seem to see the value, lol so im not sure whether its containing values :) 

Hi,

According to your code and description ,I would like to suggest you to check the link below for the similar thread which provides some solutions for the same issue.

http://forums.asp.net/p/1646901/4281893.aspx

Hope this helps.

[RESOLVED] Radiobutton event problem

Hi to all,

I am generating the forms inside a gridview which was populating dynamically, so there will be morethan one radiobuttonlist, I am writing a radiobuttonlist selected event which was inside that gridview, when I am clicking on that radiobuttonlist, the label has to be display the number on the rightside of the radiobuttonlist, but with my code the label scor value is changing in all the label of the row, the code of the radiobuttonlist event is given below.

public void Onselected(object sender, EventArgs e)
{
RadioButtonList rdolt = sender as RadioButtonList;
ObjQMDO = new QuestionTypeValueManagerDO();
ObjQMDO.QuesTypeValueID = Convert.ToInt32(rdolt.SelectedValue);
if (rdolt != null)
{

if (Gdv_categories.Rows.Count > 0)
{
foreach (GridViewRow rowmain in Gdv_categories.Rows)
{
GridView Gdv_CatQuestions = new GridView();
Gdv_CatQuestions = (GridView)rowmain.FindControl("Gdv_QuestList");

if (Gdv_CatQuestions.Rows.Count > 0)
{
foreach (GridViewRow row in Gdv_CatQuestions.Rows)
{
Label labelscore = new Label();
labelscore.ID = "labelscore";
labelscore.CssClass = "content2";
ObjQMDO.QuesScore = ObjQMDA.GetQuesMark(Convert.ToInt32(rdolt.SelectedValue));
labelscore.Text = Convert.ToString(ObjQMDO.QuesScore);
((Panel)row.FindControl("pnl")).Controls.Add(labelscore);
}
}
}
}
}
   }

the output screens was given below

Your code is very jumbled up. Let me refine your code and provide a simple solution.

public void Onselected(object sender, EventArgs e)
{
RadioButtonList rdolt = sender as RadioButtonList;
ObjQMDO = new QuestionTypeValueManagerDO();
ObjQMDO.QuesTypeValueID = Convert.ToInt32(rdolt.SelectedValue);
if (rdolt != null)
{
GridViewRow row=rdoIt.NamingContainer as GridViewRow; //There you have your gridviewrow which contains this radiobuttonlist.

Label labelscore = new Label();
labelscore.ID = "labelscore";
labelscore.CssClass = "content2";
ObjQMDO.QuesScore = ObjQMDA.GetQuesMark(Convert.ToInt32(rdolt.SelectedValue));
labelscore.Text = Convert.ToString(ObjQMDO.QuesScore);
((Panel)row.FindControl("pnl")).Controls.Add(labelscore);

}
   }

 

Ok I hope you got the idea.

 

 

actually the radiobutton was generating under Gdv_QuestList which was placed under Gdv_categories

actually the radiobutton was generating under Gdv_QuestList which was placed under Gdv_categories

actually the radiobutton was generating under Gdv_QuestList which was placed under Gdv_categories

[RESOLVED] <asp:radiobuttonlist text not wrapping

I have a asp:radiobuttonlist control.  It has 5 radiobuttons.  So for some of the radiobuttons the text is too long and not fitting in my table.  That means its wrapping to the next line.  The problem is it goes all the way to the left side below the radio button.  I want the text to align nicely when it wraps (some what similar to the bullets we use in word document)

It may not be possible with RadioButtonList, you may have to use custom control or a DataList.

This is a simple example of RadioButtonList using DataList.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        function toggleSelection(source) {
            $("#DataList1 input[id*='rb']").each(function (index) {
                $(this).attr('checked'false);
            });
            source.checked = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical" Width="300px">
        <ItemTemplate>
            <table>
                <tr>
                    <td valign="top">
                        <asp:RadioButton onclick="toggleSelection(this);" ID="rb" runat="server" />
                    </td>
                    <td>
                        <b>Sample Text Sample Text Sample Text Sample Text Sample Text Sample Text Sample Text
                            Sample Text Sample Text Sample Text Sample Text Sample Text</b>
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
    </form>
</body>
</html>

Image hosting by IMGBoot.com

It may not be possible with RadioButtonList, you may have to use custom control or a DataList.

This is a simple example of RadioButtonList using DataList.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        function toggleSelection(source) {
            $("#DataList1 input[id*='rb']").each(function (index) {
                $(this).attr('checked'false);
            });
            source.checked = true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical" Width="300px">
        <ItemTemplate>
            <table>
                <tr>
                    <td valign="top">
                        <asp:RadioButton onclick="toggleSelection(this);" ID="rb" runat="server" />
                    </td>
                    <td>
                        <b>Sample Text Sample Text Sample Text Sample Text Sample Text Sample Text Sample Text
                            Sample Text Sample Text Sample Text Sample Text Sample Text</b>
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
    </form>
</body>
</html>

 

 

Image hosting by IMGBoot.com

THis is a real good one and will definitely help me.  In the future I am planning to database the text values coming from database.  So in that case the datalist is really good.

But for now, I am just hardcoding the "text" for each radiobutton list.  In this case I cannot use Datalist since the itemtemplate has to loop some value from database.

Am I wrong or not?  if that is the case, how can I handle it for now? 

Yes, you can still use RadioButtonList with some tweaking in the ListItem Style attribute. Apply some margin for second row of text.

This may not be perfectly valid HTML Markup but you can ignore the layout warnings.

<asp:RadioButtonList runat="server" ID="RadioButtonList1" Width="300px">
    <asp:ListItem>
    Sample Text Sample Text Sample Text
    <br />
    <span style="margin-left:22px">Sample Text Sample Text Sample Text </span>
    <br />
    <span style="margin-left:22px">Sample Text Sample Text Sample Text </span>       
    </asp:ListItem>
    <asp:ListItem Text="text2"></asp:ListItem>
</asp:RadioButtonList>

This example works fine with a margin of 22 px for a RadioButotnList width 300px.

Image hosting by IMGBoot.com

You have to do a similar trial and error with your current ListItems

<div style="background-color: #dddddd; border-left: 5px solid #999999; margin: 15px 15px 15px 30px; width: 95%;"> <div style="border: 10px solid #dddddd;">

Yes, you can still use RadioButtonList with some tweaking in the ListItem Style attribute. Apply some margin for second row of text.

<asp:RadioButtonList runat="server" ID="RadioButtonList1" Width="300px">
    <asp:ListItem><div class="im">
    Sample Text Sample Text Sample Text</div>    <br />
    <span style="margin-left:22px">Sample Text Sample Text Sample Text </span>
    <br />
    <span style="margin-left:22px">Sample Text Sample Text Sample Text </span>       
    </asp:ListItem>
    <asp:ListItem Text="text2"></asp:ListItem>
</asp:RadioButtonList>

This example works fine with a margin of 22 px for a RadioButotnList width 300px.

<div class="im">

Image hosting by IMGBoot.com

</div>

You have to do a similar trial and error with your current ListItems

</div> </div>
I tried this way, but I got a message that you cannot add span tags (probably any css tags) within a list item. So instead of using a radiobuttonlist I used a html <input type radio> and set runat=server. So then I am using this in the server control to check which one checked etc. No javascript. All done in the code behind and its working. But thanks for all your help. Your datalist answer is very helpful and I will be using it in the future.

If the RadioButtonList Items Text is static, You can also define the text in CodeBehind if you are getting validation errors from the markup

RadioButtonList1.Items[0].Text = @"  Sample Text Sample Text Sample Text
                                                    <br />
                                                    <span style=""margin-left:22px"">Sample Text Sample Text Sample Text </span>
                                                    <br />
                                                    <span style=""margin-left:22px"">Sample Text Sample Text Sample Text </span>";