Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do i bind selectedvalue for radiobuttonlist in datagrid?

Status
Not open for further replies.

citizenzen

Programmer
Jun 28, 2007
102
US

I have a detailsview which is based on the selection of mastergrid. The detailsview has templatefields for editing and I included textboxes, radiobuttonlists, dropdownlists, etc. When the user chooses to edit, I need to retrieve the sql values so they can see what they previously chose. However, I am unable to successfully bind anything but the textboxes and labels. How do i bind and pull the values for my drop-downs and radiobutton lists?

The following is a sample of my bindDetails subprocedure, i tried binding just a radiobuttonlist and a dropdownlist, but I get many errors. the dropdownlist should feature not only the user's previous selection, but new options from the database.

Please advise.

Code:
SqlCommand detcomm = new SqlCommand("select * from view_shwAllMusic WHERE ID=@ID", detconn);
        DataTable mdt = new DataTable();

        try
        {
            foreach (GridViewRow abc in musicGrid.Rows)
            {
                CheckBox bCheck = (CheckBox)abc.FindControl("selectMusic");
                if (bCheck != null && bCheck.Checked)
                {
                    int Req = Convert.ToInt32(musicGrid.DataKeys[abc.RowIndex].Value);
                    detcomm.Parameters.AddWithValue("@ID", Req);

                    SqlDataAdapter joy = new SqlDataAdapter(detcomm);
                    joy.Fill(mdt);

                    //BIND TEMPLATE CONTROLS
                    RadioButtonList myvideo = (RadioButtonList)musicDetailsGV.FindControl("videoTypeRadioList");
                    DropDownList myformat = (DropDownList)musicDetailsGV.FindControl("formatDropList");
                    //new datasource for format, to pull new records
                    
                    myvideo.DataSource = mdt;
                    myvideo.SelectedValue = "Videotype";
                    myvideo.DataValueField = "VideoType";
                    myvideo.DataBind();
                }
                musicDetailsGV.AutoGenerateRows = false;
                musicDetailsGV.DataSource = mdt;
                musicDetailsGV.DataBind();
            }
 
I have datavaluefield in my code behidn above. I am getting an error with everything.
 
Try setting the property in markup or in the designer (depending on if it is a web or win-forms app)

 
in my code-behind, I get

Object reference not set to an instance of an object. , the error is supposedly with my datasource:

myvideo.DataSource = mdt;


Code:
foreach (GridViewRow abc in musicGrid.Rows)
            {
                CheckBox bCheck = (CheckBox)abc.FindControl("selectMusic");
                if (bCheck != null && bCheck.Checked)
                {
                    int Req = Convert.ToInt32(musicGrid.DataKeys[abc.RowIndex].Value);
                    detcomm.Parameters.AddWithValue("@ID", Req);

                    SqlDataAdapter joy = new SqlDataAdapter(detcomm);
                    joy.Fill(mdt);

                    //BIND TEMPLATE CONTROLS
                    RadioButtonList myvideo = (RadioButtonList)musicDetailsGV.FindControl("videoTypeRadioList");
                    DropDownList myformat = (DropDownList)musicDetailsGV.FindControl("formatDropList");
                    //new datasource for format, to pull new records
                    
                    myvideo.DataSource = mdt;
                    //myvideo.SelectedValue = "Videotype";
                    myvideo.DataValueField = "VideoType";
                    myvideo.DataBind();
                }
                musicDetailsGV.AutoGenerateRows = false;
                musicDetailsGV.DataSource = mdt;
                musicDetailsGV.DataBind();
            }
 
The cause may also be that myvideo is null. In that case, it would mean that '(RadioButtonList)musicDetailsGV.FindControl("videoTypeRadioList")' is returning null.

|| ABC
 
In your code you are looking for the rbl using the grid as it's container.

Code:
 RadioButtonList myvideo = (RadioButtonList)musicDetailsGV.FindControl("videoTypeRadioList");

You need to do the find control at the row level, as there will be a rbl for every row in your grid (right?)...

 
this is what I changed. I had a loop for my data, but now, the detailsview does not appear.

Code:
            foreach (GridViewRow abc in musicGrid.Rows)
            {
                foreach (GridViewRow detm in musicDetailsGV.Rows)
                    {
                CheckBox bCheck = (CheckBox)abc.FindControl("selectMusic");

                if (bCheck != null && bCheck.Checked)
                {
                    //added the following on 9/4/08
                        int Req = Convert.ToInt32(musicGrid.DataKeys[abc.RowIndex].Value);
                        detcomm.Parameters.AddWithValue("@ID", Req);

                        SqlDataAdapter joy = new SqlDataAdapter(detcomm);
                        joy.Fill(mdt);

                        //BIND TEMPLATE CONTROLS
                        RadioButtonList myvideo = (RadioButtonList)detm.FindControl("videoTypeRadioList");
                        //DropDownList myformat = (DropDownList)detm.FindControl("formatDropList");
                        //new datasource for format, to pull new records

                        myvideo.DataSource = mdt;
                        myvideo.SelectedValue = "Videotype";
                        //myvideo.DataValueField = "VideoType";
                        myvideo.DataTextField = "VideoType";
                        myvideo.DataBind();
                    }
                }
                musicDetailsGV.AutoGenerateRows = false;
                musicDetailsGV.DataSource = mdt;
                musicDetailsGV.DataBind();
            }
 
mdt is not empty. before i placed the template control in, i was able to successfully pull data.

please advise.
 
.aspx CODE FOR THE DETAILSVIEW - TemplateField

Code:
<asp:TemplateField HeaderText="Master/Dub" ConvertEmptyStringToNull="False">
                            <HeaderStyle Font-Bold="True" />
                            <EditItemTemplate>                            
                             <asp:Label ID="videotypelbl" runat="server" Text='<%#Bind("VideoType")%>'></asp:Label>
                                <br />
                                <asp:RadioButtonList ID="videoTypeRadioList" runat="server" Font-Size="11px" RepeatDirection="Horizontal">                           
                                    <asp:ListItem Value="0">Master</asp:ListItem>
                                    <asp:ListItem Value="1">Dub</asp:ListItem>
                                </asp:RadioButtonList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                 <asp:Label ID="orgvideotypelbl" runat="server" Text='<%#Bind("VideoType")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>


aspx.cs page for the code-behind

Code:
foreach (GridViewRow abc in musicGrid.Rows)
            {
                
                CheckBox bCheck = (CheckBox)abc.FindControl("selectMusic");
                
                RadioButtonList myvideo = (RadioButtonList)musicDetailsGV.FindControl("videoTypeRadioList");

                   if (bCheck != null && bCheck.Checked)
                    {
                        //added the following on 9/4/08
                        int Req = Convert.ToInt32(musicGrid.DataKeys[abc.RowIndex].Value);
                        detcomm.Parameters.AddWithValue("@ID", Req);

                        SqlDataAdapter joy = new SqlDataAdapter(detcomm);
                        joy.Fill(mdt);                       
                    }

                musicDetailsGV.AutoGenerateRows = false;

                //videotype radio button
                myvideo.DataSource = mdt;
                myvideo.SelectedValue = "Videotype";
                myvideo.DataTextField = "VideoType"; myvideo.DataSource = viddt;
                myvideo.DataBind();

                //binding of remainder of grid
                musicDetailsGV.DataSource = mdt;
                musicDetailsGV.DataBind();
            }
 
Given the fact that you've only posted a portion of your code I'm not 100% sure I follow exactly what your doing. However, based on the information you've provided here is my understanding:

1. You have 2 grids on your page. The first grid displays summary information and the second displays detail information.

2. When a user selects a row in the summary grid (by checking the checkbox), you wish to display the corresponding data in the details grid.

I've put together the following example based on my understanding. A few things to note... 1) the code-behind you posted yesterday is slightly different than what you posted today. In today's code MyVideo is being assigned a DataSource of mdt and then being assigned a DataSource of viddt before calling DataBind(). 2) you are still looking for the rbl using the grid as it's container; does this mean there will only ever be one row in the details view at a given time? In my example I am assuming this is the case. 3) Your order of operations seems to be off.. You are attempting to bind to the rbl before you are populating the Details grid; you should populate the details grid first. 4) It seems that you may be cofusing what DataBind actually does to the rbl. By giving it a DataSource and binding it you are creating a ListItem for each row in your DataSource inside the rbl. It appears that you are trying to select one of the ListItems which is hard-coded in your markup rather than binding a new list to the rbl. All that being said, here is the example I came up with. This may not translate exactly into what you are doing, but hopefully will serve as a good illustration.

Mark-up
Code:
<table>
    <tr>
        <td>Music Grid</td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="gvMusic" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="cbSelectMusic" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                </Columns>
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>Details Grid</td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="lblVideoType" runat="server" Text='<%#Bind("VideoType")%>'></asp:Label>
                            <br />
                            <asp:RadioButtonList ID="rblVideoType" runat="server" RepeatDirection="Horizontal" >
                                <asp:ListItem Value="0" Text="Master"></asp:ListItem>
                                <asp:ListItem Value="1" Text="Dub"></asp:ListItem>
                            </asp:RadioButtonList>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnViewDetails" runat="server" Text="View Details" OnClick="btnViewDetails_Click" />
        </td>
    </tr>
</table>

Code-Behind
Code:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        PopulateMusicGrid();
}
private void PopulateMusicGrid()
{
    //Create fake DataSource for sake of illustration
    DataTable dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    for (int i = 1; i < 6; i++)
    {
        DataRow dr = dt.NewRow();
        dr["Id"] = i.ToString();
        dr["Name"] = "Song " + i.ToString();
        dt.Rows.Add(dr);
    }
    gvMusic.DataSource = dt;
    gvMusic.DataBind();
}
private DataTable CreateDetailsDataSource(int key)
{
    //Create fake data source using gvMusic's selected DataKey
    DataTable dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    dt.Columns.Add("VideoType");
    DataRow dr = dt.NewRow();
    dr["Id"] = key.ToString();
    dr["Name"] = "Song " + key.ToString();
    dr["VideoType"] = key % 2 == 0 ? "Master" : "Dub";
    dt.Rows.Add(dr);
    return dt;
    
}
protected void btnViewDetails_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvMusic.Rows)
    {
        //Find Check box
        CheckBox check = (CheckBox)row.FindControl("cbSelectMusic");
        if (check != null && check.Checked)
        {
            //Get DataKey
            int key = int.Parse(gvMusic.DataKeys[row.RowIndex].Value.ToString());
            //Get DataSource for gvDetails and bind it
            DataTable dt = CreateDetailsDataSource(key);
            gvDetails.DataSource = dt;
            gvDetails.DataBind();
            //find radio button list (this code assumes there will only be one row in the details grid)
            RadioButtonList rbl = (RadioButtonList)gvDetails.Rows[0].FindControl("rblVideoType");
            //find video type label to determine which rbl item should be selected
            Label lbl = (Label)gvDetails.Rows[0].FindControl("lblVideoType");
            //select correct rbl item based on label text
            if (lbl.Text == "Master")
                rbl.SelectedValue = "0";
            if (lbl.Text == "Dub")
                rbl.SelectedValue = "1";
        }

    }
}

Hope this helps

 
Hello KDavie.

Thanks for your feedback. I do have 2 grids- a master grid and a details grid. The detailsview may have radiobuttonlists and dropdownlists. I am a bit confused, as I essentially need to be able to show the user what they initially selected in the radiobuttonlist or dropdownlist. Is there no need to bind twice? And as I have updated my subprocedure, I am getting the error: Object reference not set to an instance of an object. I am trying to get the values from the edittemplate area and it seems to only show the itemtemplate area. please advise.

updated code:

Code:
    protected void musicDetailsGV_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        vidGridResultslbl.Visible = true;
        if (e.CommandName=="Edit")
        {
            bindMusicDetails();
            vidGridResultslbl.Text = "You are in edit mode";
            musicDetailsGV.ChangeMode(DetailsViewMode.Edit);
        }
        else if (e.CommandName == "Update")
        {
            bindMusicDetails();
            vidGridResultslbl.Text = "You are in update mode";
        }
        else if (e.CommandName == "Cancel")
        {
            vidGridResultslbl.Text = "You are in cancel mode";
            musicDetailsGV.ChangeMode(DetailsViewMode.ReadOnly);
        }
    }

private void bindMusicDetails()
    {
        detErrors.Visible = false;
        musicDetailsGV.Visible = true;
        
        string showdet = ConfigurationManager.ConnectionStrings["RevisedTapeLibrary"].ConnectionString;
        SqlConnection detconn = new SqlConnection(showdet);
        SqlCommand detcomm = new SqlCommand("select * from view_shwAllMusic WHERE ID=@ID", detconn);
        DataTable mdt = new DataTable();
        try
        {
            foreach (GridViewRow abc in musicGrid.Rows)
            {
                CheckBox bCheck = (CheckBox)abc.FindControl("selectMusic");
                if (bCheck != null && bCheck.Checked)
                {
                    //added the following on 9/4/08
                    int Req = Convert.ToInt32(musicGrid.DataKeys[abc.RowIndex].Value);
                    detcomm.Parameters.AddWithValue("@ID", Req);

                    SqlDataAdapter joy = new SqlDataAdapter(detcomm);
                    joy.Fill(mdt);

                    musicDetailsGV.AutoGenerateRows = false;
                    musicDetailsGV.DataSource = mdt;

                    musicDetailsGV.DataBind();              
                
                //these labels are in the edittemplate area
                    RadioButtonList rblVideo = (RadioButtonList)musicDetailsGV.Rows[1].FindControl("videoTypeRadioList");

                    Label lblUpdVid = (Label)musicDetailsGV.Rows[1].FindControl("videotypelbl");

                //this label is in the itemtemplate area
                    Label lblVid = (Label)musicDetailsGV.Rows[1].FindControl("orgvideotypelbl");

                   if (lblVid.Text == "Master")
                    {
                        rblVideo.SelectedValue = "0";
                    }
                    else
                    {
                        rblVideo.SelectedValue = "1";
                    }
                }
            }
        }
        catch (SqlException risk)
        {
            detErrors.Text = "Error binding details<br>" + risk;
        }
    }
 
In order to find controls within the edit template you'll need to be in edit mode. You may consider moving this portion of your code to the RowEditing event of the GridView. Also, as a safety you can check what mode you're in before executing that code, for example:

Code:
if (abc.RowState == DataControlRowState.Edit)
{
    //these labels are in the edittemplate area
    RadioButtonList rblVideo = (RadioButtonList)musicDetailsGV.Rows[1].FindControl("videoTypeRadioList");

    Label lblUpdVid = (Label)musicDetailsGV.Rows[1].FindControl("videotypelbl");

    //this label is in the itemtemplate area
    Label lblVid = (Label)musicDetailsGV.Rows[1].FindControl("orgvideotypelbl");

    if (lblVid.Text == "Master")
    {
        rblVideo.SelectedValue = "0";
    }
    else
    {
        rblVideo.SelectedValue = "1";
    }
}



 
Thank you KDavie, I am not getting as many errors, but the database values are not being selected.

For the detailsview, i placed the above code in the ItemCommand and then I switched the code to modeChanging event. i tried row-editing, but I don't get any of the response.writes to indicate which state I am in. So, I placed the code in the ModeChanging event (ItemCommand Event didn't work). When I click to 'edit' a record from the main grid, ModeChanging Event tells me that I am in 'Edit Mode', but nothing is being pulled for the radiobuttonLists. what can be done to select the proper choice in the list?:

Code:
protected void musicDetailsGV_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
        foreach (GridViewRow ste in musicGrid.Rows)
        {
            CheckBox hu = (CheckBox)ste.FindControl("selectMusic");
            {
                musicDetailsGV.ChangeMode(e.NewMode);
                bindMusicDetails();
                musicErrorTxt.Text = "Current Mode " + e.NewMode;

                //bindMusicDetails();
                //}
                //if (ste.RowState == DataControlRowState.Edit)                
                    if (ste.RowState == DataControlRowState.Edit)
                    {
                        RadioButtonList ddlVidType = (RadioButtonList)musicDetailsGV.FindControl("rblVideoType");
                        //label in the itemtemplate
                        Label lblorgVal = (Label)musicDetailsGV.FindControl("orgvideotypelbl");
                        Label lblEditVal = (Label)musicDetailsGV.FindControl("videotypelbl");
                        musicErrorTxt.Visible = true;

                        if (lblorgVal.Text == "Master")
                        {
                            ddlVidType.SelectedValue = "0";
                            Response.Write("You chose a master");
                        }
                        else
                        {
                            ddlVidType.SelectedValue = "1";
                            Response.Write("You chose a dub");
                        }
                        //musicDetailsGV.ChangeMode(DetailsViewMode.Edit);                        
                    }
        }
       }
                    
    }

 
I've modified my previous example to illustrate your desired functionality:

Markup:
Code:
<table>
    <tr>
        <td>Music Grid</td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="gvMusic" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="cbSelectMusic" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                </Columns>
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>Details Grid</td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" OnRowEditing="gvDetails_RowEditing">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:TemplateField HeaderText="Video Type">
                        <ItemTemplate>
                        <asp:Label ID="lblVideoType" runat="server" Text='<%#Bind("VideoType")%>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:Label ID="lblVideoType" runat="server" Text='<%#Bind("VideoType")%>'></asp:Label>   
                            <br />                     
                            <asp:RadioButtonList ID="rblVideoType" runat="server" Font-Size="11px" RepeatDirection="Horizontal">                           
                                <asp:ListItem Value="0" Text="Master"></asp:ListItem>
                                <asp:ListItem Value="1" Text="Dub"></asp:ListItem>
                            </asp:RadioButtonList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnViewDetails" runat="server" Text="View Details" OnClick="btnViewDetails_Click" />
        </td>
    </tr>
</table>

CodeBehind:

Code:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        PopulateMusicGrid();
}
private void PopulateMusicGrid()
{
    //Create fake DataSource for sake of illustration
    DataTable dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    for (int i = 1; i < 6; i++)
    {
        DataRow dr = dt.NewRow();
        dr["Id"] = i.ToString();
        dr["Name"] = "Song " + i.ToString();
        dt.Rows.Add(dr);
    }
    gvMusic.DataSource = dt;
    gvMusic.DataBind();
}
private DataTable CreateDetailsDataSource(int key)
{
    //Create fake data source using gvMusic's selected DataKey
    DataTable dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    dt.Columns.Add("VideoType");
    DataRow dr = dt.NewRow();
    dr["Id"] = key.ToString();
    dr["Name"] = "Song " + key.ToString();
    dr["VideoType"] = key % 2 == 0 ? "Master" : "Dub";
    dt.Rows.Add(dr);
    return dt;
    
}
protected void btnViewDetails_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvMusic.Rows)
    {
        //Find Check box
        CheckBox check = (CheckBox)row.FindControl("cbSelectMusic");
        if (check != null && check.Checked)
        {
            //Get DataKey
            int key = int.Parse(gvMusic.DataKeys[row.RowIndex].Value.ToString());
            //Get DataSource for gvDetails and bind it
            DataTable dt = CreateDetailsDataSource(key);
            gvDetails.DataSource = dt;
            gvDetails.DataBind();
            gvDetails.EditIndex = 0;
        }

    }
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvDetails.EditIndex = e.NewEditIndex;
    //find radio button list (this code assumes there will only be one row in the details grid)
    RadioButtonList rbl = (RadioButtonList)gvDetails.Rows[0].FindControl("rblVideoType");
    //find video type label to determine which rbl item should be selected
    Label lbl = (Label)gvDetails.Rows[0].FindControl("lblVideoType");
    //select correct rbl item based on label text
    if (lbl.Text == "Master")
       rbl.SelectedValue = "0";
    if (lbl.Text == "Dub")
        rbl.SelectedValue = "1";

}

Let me know how it works out for you.

-Kevin

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top