Click here to Skip to main content
15,901,853 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am programmatically adding comboboxes per each column count from a gridview. the gridview gets its column counts from an excel sheet being uploaded from another page. HOwever, i want to know lets say there are 20 columns in the gridview and i have 20 drop down list items added to the page. how can i tell which drop down list item was selected. each drop down is correlated to a row. so if there are 20 rows there are 20 drop down list items. Please help. Thanks.

DONT DOWN VOTE please help me understand my mistake in asking the question. THANKS

VB
trLists.Cells.Clear()
            For i As Integer = 0 To GridView1.Rows(0).Cells.Count - 1
                Dim dd1 As New DropDownList()
                dd1.ID = "dd1" + i.ToString()
                dd1.Width = Unit.Pixel(150)
                If GlobalVariable.Flag = "1B" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough/Zip Code")
                    dd1.Items.Add("Address No.")
                    dd1.Items.Add("Street Name")
                    dd1.Items.Add("Freeform")
                ElseIf GlobalVariable.Flag = "2" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough/Zip Code")
                    dd1.Items.Add("Street 1")
                    dd1.Items.Add("Street 2")
                ElseIf GlobalVariable.Flag = "3" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough/Zip Code")
                    dd1.Items.Add("On Street")
                    dd1.Items.Add("First Cross Street")
                    dd1.Items.Add("Second Cross Street")
                    dd1.Items.Add("Side Of The Street")
                ElseIf GlobalVariable.Flag = "3S" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough/Zip Code")
                    dd1.Items.Add("On Street")
                    dd1.Items.Add("First Cross Street")
                    dd1.Items.Add("Second Cross Street")
                ElseIf GlobalVariable.Flag = "BL" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough/Zip Code")
                    dd1.Items.Add("Block")
                    dd1.Items.Add("Lot")
                ElseIf GlobalVariable.Flag = "BN" Then
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("BIN Number")
                Else
                    dd1.Items.Insert(0, New ListItem(String.Empty, String.Empty))
                    dd1.Items.Add("Borough")
                    dd1.Items.Add("Street Name")
                End If
                Dim cell As New TableCell()
                cell.Controls.Add(dd1)
                trLists.Cells.Add(cell)
                GlobalVariable.dd1 = dd1
            Next


What I have tried:

i tried to post the same question on stack overflow but no one got it i think. this is why i chose code project.
Posted
Updated 7-Jul-16 6:01am

To make it more clear to your side, I made another demo. We will add a Table, HiddenField, GridView and a Button control in the markup.

ASPX:
ASP.NET
<asp:table id="tbl1" runat="server" />
<asp:hiddenfield id="HiddenField1" runat="server" />
<asp:gridview id="GridView1" runat="server">
</asp:gridview>
<asp:button id="Button1" runat="server" onclick="Button1_Click" text="Button"/>


The table is where we generate the DropDownList based
The HiddenField is where we store the selected DropDown ID at SelectedIndexChanged event of DropDown
The GridView contains your data
The Button is where we get the value from HiddenField and display in a Message Box (alert)

Now here's the code block:

VB.NET
VB
Protected Sub Page_Load(sender As Object, e As EventArgs)
	If Not IsPostBack Then
			'bind  your grid here
		BindGridView()
	End If

	GenerateDropDowns(GridView1.Columns.Count)
End Sub

Private Sub GenerateDropDowns(colCount As Integer)

	Dim row As New TableRow()
	For i As Integer = 0 To colCount - 1
		Dim cell As New TableCell()
		Dim ddl As New DropDownList()
		ddl.ID = "ddl" + i.ToString()
		ddl.Items.Add(New ListItem("PASS", "P"))
		ddl.Items.Add(New ListItem("FAIL", "F"))
		ddl.AutoPostBack = True
		'wire up the event
		AddHandler ddl.SelectedIndexChanged, AddressOf OnSelectedIndexChanged

		cell.Controls.Add(ddl)

		row.Cells.Add(cell)
	Next
	tbl1.Rows.Add(row)
End Sub

Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
	Dim ddl1 As DropDownList = DirectCast(sender, DropDownList)
	HiddenField1.Value = ddl1.ID
End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs)
	Dim theDropDown As String = HiddenField1.Value
	If theDropDown <> String.Empty Then
		Dim msgScript As String = String.Format("alert('You have selected: {0}');", theDropDown)
		Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "Alert", msgScript, True)

			'reset
		HiddenField1.Value = String.Empty
	End If
End Sub


C# Equivalent:
C#
protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        BindGridView();//bind  your grid here
    }

    GenerateDropDowns(GridView1.Columns.Count);
}

private void GenerateDropDowns(int colCount) {

    TableRow row = new TableRow();
    for (int i = 0; i < colCount; i++) {
        TableCell cell = new TableCell();
        DropDownList ddl = new DropDownList();
        ddl.ID = "ddl" + i.ToString();
        ddl.Items.Add(new ListItem("PASS", "P"));
        ddl.Items.Add(new ListItem("FAIL", "F"));
        ddl.AutoPostBack = true;
       //wire up the event
        ddl.SelectedIndexChanged += OnSelectedIndexChanged;

        cell.Controls.Add(ddl);
        row.Cells.Add(cell);

    }
    tbl1.Rows.Add(row);
}

protected void OnSelectedIndexChanged(object sender, EventArgs e) {
    DropDownList ddl1 = (DropDownList)sender;
    HiddenField1.Value = ddl1.ID;
}

protected void Button1_Click(object sender, EventArgs e) {
    string theDropDown = HiddenField1.Value;
    if (theDropDown != string.Empty) {
        string msgScript = string.Format("alert('You have selected: {0}');", theDropDown);
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", msgScript, true);

        HiddenField1.Value = string.Empty;//reset
    }
}


Hope that helps and clears your confusion.
 
Share this answer
 
v2
Comments
JT1992 23-Jun-16 16:01pm    
the aspx in this code is not working. not sure why.
Vincent Maverick Durano 24-Jun-16 8:55am    
by the way, the code is just to give you an idea and it will not display anything because I have not included the code for binding the gridview. In order for it to work you should bind the grid with data.
Vincent Maverick Durano 28-Jun-16 9:34am    
are you able to get it working now?
Vincent Maverick Durano 24-Jun-16 8:53am    
i've edited the code try it now
CHill60 24-Jun-16 9:39am    
It gets a bit confusing when you post multiple answers to the same question - which one is supposed to be the solution? Better to use the Improve solution link
You could wire-up the SelectedIndexChanged event of your DropDown. At SelectedIndexChanged event handler, you could cast the sender of the control to determine which row your triggered the DropDown event. For example:

Wireup the event:
C#
dd1.SelectedIndexChanged += OnSelectedIndexChanged;


VB.NET
VB
AddHandler dd1.SelectedIndexChanged, AddressOf OnSelectedIndexChanged


Then you can write the code to access the selected item like:

C#
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e){
        DropDownList ddl1 = (DropDownList)sender;
        GridViewRow row = (GridViewRow)ddl1.NamingContainer;
        if (row != null)
        {
            string selectedItem = ddl1.SelectedItem.Text;
        }
}


VB.NET
VB
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
	Dim ddl1 As DropDownList = DirectCast(sender, DropDownList)
	Dim row As GridViewRow = DirectCast(ddl1.NamingContainer, GridViewRow)
	If row IsNot Nothing Then
		Dim selectedItem As String = ddl1.SelectedItem.Text
	End If
End Sub
 
Share this answer
 
v3
Comments
JT1992 21-Jun-16 11:59am    
ahh let me try this and i will give you a quick reply. this seems to be what i was looking for.
Richard Deeming 21-Jun-16 12:05pm    
VB doesn't use += to wire up event handlers - it uses AddHandler:
AddHandler dd1.SelectedIndexChanged, OnSelectedIndexChanged

And you haven't need the new EventHandler(...) decorator in VB or C# since .NET 1.0 - the compiler is smart enough to add that for you. :)
dd1.SelectedIndexChanged += OnSelectedIndexChanged;
Vincent Maverick Durano 21-Jun-16 12:18pm    
I'm not a VB guy and I'm just using a converter tool to convert it to VB. So blame the tool ;) I updated my reply to add the correct syntax.

Thanks for the information. Much appreciated man! :)
JT1992 21-Jun-16 12:28pm    
wait i am lost i dont get it so what should i use for code for the event handler?
the one listed above gives me to use a RaiseEvent Statement
Vincent Maverick Durano 21-Jun-16 12:31pm    
Try this:

AddHandler dd1.SelectedIndexChanged, AddressOf OnSelectedIndexChanged
Ok here's the other solution to your problem. The idea is use HiddenField control to store the selected rowIndex. Here's the demo code below:

ASPX:

ASP.NET
<asp:content id="Content2" contentplaceholderid="MainContent" runat="server" xmlns:asp="#unknown">
    <asp:gridview id="GridView1" runat="server" onrowcreated="GridView1_RowCreated">
        <columns>
                <asp:templatefield>
                    <itemtemplate>
                        <asp:hiddenfield id="HiddenField1" runat="server" value="0" />
                    </itemtemplate>
                </asp:templatefield>
         </columns>
    </asp:gridview>
    <asp:button id="Button1" runat="server" onclick="Button1_Click" text="Button" />
</asp:content>


CODE BEHIND:
C#
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;

namespace WebFormDemo
{
    public partial class DynamicControlInGridView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack)
                BindGridView();
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                DropDownList ddlResult = new DropDownList();
                ddlResult.ID = "ddlResult";
               
                ddlResult.Items.Add(new ListItem("PASS", "P"));
                ddlResult.Items.Add(new ListItem("FAIL", "F"));
                ddlResult.AutoPostBack = true;
                ddlResult.SelectedIndexChanged += OnSelectedIndexChanged;

                e.Row.Cells[0].Controls.Add(ddlResult);

            }
        }

        protected void OnSelectedIndexChanged(object sender, EventArgs e) {
            DropDownList ddl1 = (DropDownList)sender;
            GridViewRow row = (GridViewRow)ddl1.NamingContainer;
            if (row != null) {
                HiddenField hf = (HiddenField)row.FindControl("HiddenField1");
                hf.Value = row.RowIndex.ToString();
            }
        }

        private void BindGridView() {
            GridView1.DataSource = CreateDataSource();
            GridView1.DataBind();
        }

        public DataTable CreateDataSource() {
            DataTable dt = new DataTable();
            DataRow dr;

            dt.Columns.Add(new DataColumn("ID", typeof(string)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Lastname", typeof(string)));

            for (int i = 0; i < 20; i++) {
                dr = dt.NewRow();

                dr[0] = i;
                dr[1] = "Name" + i.ToString();
                dr[1] = "Last Name" + i.ToString();

                dt.Rows.Add(dr);
            }

            return dt;
        }

        protected void Button1_Click(object sender, EventArgs e) {

            foreach (GridViewRow row in GridView1.Rows) {
                HiddenField hf = (HiddenField)row.FindControl("HiddenField1");
                if (hf != null) {
                    int selectedRowIndex = Convert.ToInt32(hf.Value);
                    if (selectedRowIndex > 0) {
                        string msgScript = string.Format("alert('You have selected: {0}');", selectedRowIndex);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", msgScript, true);

                        hf.Value = "0";//reset
                        break;
                    }
                }              
            }
        }
       
    }
}


That should work. The code above is in C#. You may need to convert it VB before applying it. Hope that helps.
 
Share this answer
 
Comments
JT1992 22-Jun-16 15:43pm    
hey is there a way i can show you an image of what my page will look like?
JT1992 22-Jun-16 15:43pm    
because i believe you think that the drop down lists are inside the gridview in which they are not they are separate div objects. but i want to know when i select like lets say a value called test from the drop down. i want to know which drop down list object i selected.
Vincent Maverick Durano 23-Jun-16 6:24am    
You should have mentioned that in the first place. You said your dropdowns are rendered in the rows. If i were you, I would use a repeater control to generate those dropdown instead.
Vincent Maverick Durano 23-Jun-16 8:13am    
If you just need to determine which dropdown you selected then you can still use the same approch by casting the sender of the object who triggers the selecteindexchangedevent. But this time you just need to get the ID of the dropdown to determine which dropdown you selected:

Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddl1 As DropDownList = DirectCast(sender, DropDownList)
Dim id As String = ddl1.ID
End Sub
JT1992 23-Jun-16 10:07am    
ahh i am not really sure how i would be able to do that. is it possible to do it with the code i have above?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900