473,387 Members | 1,771 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

access values from dynamic generated textbox (or dropdownlist) in a gridview

6
In my asp page when press a button, a gridview will be populated with data from db, but beside the columns from database i need a new dynamic column in gridview, to contain only dropdownlist with items number from 0-n.


This far i managed to do it, with some research on internet (i used an intemerdiet datatable to apply ItemTemplate from GridViewTemplate class, and than merged it to datatable containg the result from query, so the gridview's datasource si the merge of this 2 datatables).


The issue is that i don't now how can i access the values selected by user in the dinamically dropdownlists, 'cause i have to save them in DB.


Attach is my GridViewTemplate class code, and .cs and .aspx code.

GridViewTemplate class
Expand|Select|Wrap|Line Numbers
  1. public class GridViewTemplate : ITemplate
  2. {
  3.     //A variable to hold the type of ListItemType.
  4.     ListItemType _templateType;
  5.  
  6.     //A variable to hold the column name.
  7.     string _columnName;
  8.  
  9.     //Constructor where we define the template type and column name.
  10.     public GridViewTemplate(ListItemType type, string colname)
  11.     {
  12.         //Stores the template type.
  13.         _templateType = type;
  14.  
  15.         //Stores the column name.
  16.         _columnName = colname;
  17.     }
  18.  
  19.     void ITemplate.InstantiateIn(System.Web.UI.Control container)
  20.     {
  21.         switch (_templateType)
  22.         {
  23.             case ListItemType.Header:
  24.                 //Creates a new label control and add it to the container.
  25.                 Label lbl = new Label();            //Allocates the new label object.
  26.                 lbl.Text = _columnName;             //Assigns the name of the column in the lable.
  27.                 container.Controls.Add(lbl);        //Adds the newly created label control to the container.
  28.                 break;
  29.  
  30.             case ListItemType.Item:
  31.                 //Creates a new dro down list control and add it to the container.
  32.                 DropDownList ddl = new DropDownList();                     //Allocates the new text box object.
  33.                 ddl.DataBinding += new EventHandler(ddl_DataBinding);      //Attaches the data binding event.
  34.                 ddl.Width = 35;                                            //Creates a column with size 4.
  35.                 ddl.Items.Add("0");                                        //Fill in the dropdownlist with values from 0-4
  36.                 ddl.Items.Add("1");
  37.                 ddl.Items.Add("2");
  38.                 ddl.Items.Add("3");
  39.                 ddl.Items.Add("4");
  40.                 //ddl.ID = "dropdownlist1";                                 // the ddl name will end with dropdownlist1, all of them, can use findcontrol method...but..
  41.                 container.Controls.Add(ddl);                              //Adds the newly created textbox to the container.
  42.                 break;
  43.  
  44.             case ListItemType.EditItem:
  45.                 //As, I am not using any EditItem, I didnot added any code here.
  46.                 break;
  47.  
  48.             case ListItemType.Footer:
  49.                 CheckBox chkColumn = new CheckBox();
  50.                 chkColumn.ID = "Chk" + _columnName;
  51.                 container.Controls.Add(chkColumn);
  52.                 break;
  53.         }
  54.     }
  55.  
  56.     void ddl_DataBinding(object sender, EventArgs e)
  57.     {
  58.         DropDownList ddd = (DropDownList)sender;
  59.         GridViewRow container = (GridViewRow)ddd.NamingContainer;
  60.         object dataValue = DataBinder.Eval(container.DataItem, _columnName);
  61.         if (dataValue != DBNull.Value)
  62.         {
  63.             ddd.Text = dataValue.ToString();
  64.         }
  65.     }
  66. }

.cs code


Expand|Select|Wrap|Line Numbers
  1. public void btn_Matrix_Click(object sender, EventArgs e)
  2.         {
  3.             SqlConnection conn = null;
  4.             SqlDataAdapter myDataAdapter = null;
  5.             grdMatrix.Visible = true;
  6.  
  7.             try
  8.             {
  9.                 string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  10.                 conn = new SqlConnection(connStr);
  11.  
  12.                 DataSet myDataSet = new DataSet();
  13.  
  14.                 myDataAdapter = new SqlDataAdapter("", conn);
  15.                 myDataAdapter.SelectCommand.CommandText = "select employee_id as 'Employee No',lastname as 'Employee Name' from employee";
  16.  
  17.  
  18.                 myDataAdapter.Fill(myDataSet, "Temp");
  19.  
  20.                 DataTable dtquery = myDataSet.Tables[0];
  21.  
  22.                 DataTable dtcolumns = new DataTable();
  23.  
  24.                 dtcolumns.Columns.Add("Level");
  25.  
  26.                foreach (DataColumn col in dtcolumns.Columns)
  27.                 {
  28.                     //Declare the bound field and allocate memory for the bound field.
  29.                     TemplateField bfield = new TemplateField();
  30.  
  31.                     //Initalize the DataField value.
  32.                     bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
  33.  
  34.                     //Initialize the HeaderText field value.
  35.                     bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
  36.  
  37.                     //Add the newly created bound field to the GridView.
  38.                     grdMatrix.Columns.Add(bfield);
  39.                 }
  40.  
  41.             dtcolumns.Merge(dtquery);
  42.             //Initialize the DataSource
  43.             grdMatrix.DataSource = dtcolumns;
  44.  
  45.             //Bind the datatable with the GridView.
  46.             grdMatrix.DataBind();
  47.             conn.Close();   
  48.             }
  49.             catch (Exception ex)
  50.             {
  51.                 WebMsgBox.Show(ex.Message);
  52.             }
  53.             finally
  54.             {
  55.                 if (conn != null)
  56.                     conn.Close();
  57.             }
  58.         }

.aspx code
Expand|Select|Wrap|Line Numbers
  1.     <br/><asp:Panel ID="Panel1" runat="server">
  2.     <asp:GridView ID="grdMatrix" runat="server" AutoGenerateColumns = "False"
  3.         CellPadding="4" EnableModelValidation="True" ForeColor="#333333"
  4.         GridLines="None" >
  5.         <AlternatingRowStyle BackColor="White" />
  6.     <Columns>
  7.     <asp:BoundField DataField="Employee No" Visible="true" HeaderText="Employee No" />
  8.     <asp:BoundField DataField="Employee Name" Visible="true" HeaderText="Employee Name" />
  9.     </Columns>
  10.         <EditRowStyle BackColor="#2461BF" />
  11.         <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  12.         <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  13.         <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  14.         <RowStyle BackColor="#EFF3FB" />
  15.         <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  16.     </asp:GridView>
  17.     </asp:Panel>
Thank you in advance.
Aug 31 '10 #1

✓ answered by Frinavale

You need to give the DropDownList an ID. Either pass the column number into the constructor for the ITemplate and use that to create the ID for the DropDownList...or in the method that handles the DropDownList binding event use the NamingContainer to retrieve the GridView.Rows.Count value and use that to create an ID for the DropDownList.

I think the first one is a bit easier to understand...but they will both accomplish the same thing.

For example, you would change the constructor to take the "colnum" value and use that to set the ID of the DropDownList in the InstantiateIn method.

Like this:
Expand|Select|Wrap|Line Numbers
  1. public class GridViewTemplate : ITemplate
  2. {
  3.     //A variable to hold the type of ListItemType.
  4.     ListItemType _templateType;
  5.  
  6.     //A variable to hold the column name.
  7.     string _columnName;
  8.  
  9.     //A variable to hold the column number.
  10.     string columnNum;
  11.  
  12.     //Constructor where we define the template type and column name.
  13.     public GridViewTemplate(ListItemType type, string colname, int colNum)
  14.     {
  15.         //Stores the template type.
  16.         _templateType = type;
  17.  
  18.         //Stores the column name.
  19.         _columnName = colname;
  20.  
  21.         //Stores the column number.
  22.         columnNum = colNum;
  23.     }
  24.  
  25.     void ITemplate.InstantiateIn(System.Web.UI.Control container)
  26.     {
  27.         switch (_templateType)
  28.         {
  29.            //...........
  30.  
  31.                 case ListItemType.Item:
  32.                 //Creates a new drop down list control and add it to the container.
  33.                   DropDownList ddl = new DropDownList();                     //Allocates the new text box object.
  34.                   ddl.DataBinding += new EventHandler(ddl_DataBinding);      //Attaches the data binding event.
  35.                   ddl.Width = 35;                                            //Creates a column with size 4.
  36.                   ddl.Items.Add("0");                                          //Fill in the dropdownlist with values from 0-4
  37.                   ddl.Items.Add("1");
  38.                   ddl.Items.Add("2");
  39.                   ddl.Items.Add("3");
  40.                   ddl.Items.Add("4");
  41.                   ddl.ID = "dropdownlist" & columnNum.ToString();                                 
  42.                   container.Controls.Add(ddl);
  43.                   //Adds the newly created textbox to the container.
  44.                 break;

Or, you try using the NamingContainer to retrieve a reference to the GridView when the DropDownList is being bound. That way you can figure out the number of columns already in the GridView to create the ID for the DropDownList. In this case you don't have to change the consturctor.

I don't really have a way to test this...but your code would look something like:
Expand|Select|Wrap|Line Numbers
  1.     void ddl_DataBinding(object sender, EventArgs e)
  2.     {
  3.         DropDownList ddd = (DropDownList)sender;
  4.         GridViewRow container = (GridViewRow)ddd.NamingContainer;
  5.  
  6.      GridView gv = (GridView)container.NamingContainer;
  7.      int rowCount = gv.Rows.Count;
  8.      ddd.ID = "dropdownlist" & rowCount.ToString();
  9.  
  10.         object dataValue = DataBinder.Eval(container.DataItem, _columnName);
  11.         if (dataValue != DBNull.Value)
  12.         {
  13.             ddd.Text = dataValue.ToString();
  14.         }
  15.     }
In your button click event you need to retrieve the GridViewRow that you want to use and call the FindControl method for each DropDownList on it like this:
Expand|Select|Wrap|Line Numbers
  1. List<DropDownList> ddlListsForRow1;
  2. ddlListsForRow1= new List<DropDownList>();
  3.  
  4. int dropDownListIteration;
  5.  
  6. for(dropDownListIteration=0; dropDownListIteration<numOfDropDownLists; i++)
  7. {
  8.   DropDownList ddl = (DropDownList))grdMatrix.Rows[1].FindControl("dropdownlist" & dropDownListIteration);
  9.   ddlListsForRow1.Add(ddl);
  10. }
  11.  
-Frinny

4 7243
Frinavale
9,735 Expert Mod 8TB
In your InstantiateIn method...when you create the DropDownList, give the DropDownList and ID. That way you can use the GridViewRow's FindControl() method to retrieve the DropDownList in the button click event.


-Frinny
Aug 31 '10 #2
sasha3
6
I have considered this, but i commented the
//ddl.ID = "dropdownlist1"; from the InstantiateIn method because i could not use it.

If i go for something like:
(DropDownList) txt1 = (DropDownList))grdMatrix.Rows[1].Cells[1].FindControl("dropdownlist1");
(DropDownList))grdMatrix.Rows[1].Cells[2].FindControl("dropdownlist2");.....and so on ...but i don't know how many dropdownlist i will have until the user makes his selections and the gridview is generated.
Aug 31 '10 #3
Frinavale
9,735 Expert Mod 8TB
You need to give the DropDownList an ID. Either pass the column number into the constructor for the ITemplate and use that to create the ID for the DropDownList...or in the method that handles the DropDownList binding event use the NamingContainer to retrieve the GridView.Rows.Count value and use that to create an ID for the DropDownList.

I think the first one is a bit easier to understand...but they will both accomplish the same thing.

For example, you would change the constructor to take the "colnum" value and use that to set the ID of the DropDownList in the InstantiateIn method.

Like this:
Expand|Select|Wrap|Line Numbers
  1. public class GridViewTemplate : ITemplate
  2. {
  3.     //A variable to hold the type of ListItemType.
  4.     ListItemType _templateType;
  5.  
  6.     //A variable to hold the column name.
  7.     string _columnName;
  8.  
  9.     //A variable to hold the column number.
  10.     string columnNum;
  11.  
  12.     //Constructor where we define the template type and column name.
  13.     public GridViewTemplate(ListItemType type, string colname, int colNum)
  14.     {
  15.         //Stores the template type.
  16.         _templateType = type;
  17.  
  18.         //Stores the column name.
  19.         _columnName = colname;
  20.  
  21.         //Stores the column number.
  22.         columnNum = colNum;
  23.     }
  24.  
  25.     void ITemplate.InstantiateIn(System.Web.UI.Control container)
  26.     {
  27.         switch (_templateType)
  28.         {
  29.            //...........
  30.  
  31.                 case ListItemType.Item:
  32.                 //Creates a new drop down list control and add it to the container.
  33.                   DropDownList ddl = new DropDownList();                     //Allocates the new text box object.
  34.                   ddl.DataBinding += new EventHandler(ddl_DataBinding);      //Attaches the data binding event.
  35.                   ddl.Width = 35;                                            //Creates a column with size 4.
  36.                   ddl.Items.Add("0");                                          //Fill in the dropdownlist with values from 0-4
  37.                   ddl.Items.Add("1");
  38.                   ddl.Items.Add("2");
  39.                   ddl.Items.Add("3");
  40.                   ddl.Items.Add("4");
  41.                   ddl.ID = "dropdownlist" & columnNum.ToString();                                 
  42.                   container.Controls.Add(ddl);
  43.                   //Adds the newly created textbox to the container.
  44.                 break;

Or, you try using the NamingContainer to retrieve a reference to the GridView when the DropDownList is being bound. That way you can figure out the number of columns already in the GridView to create the ID for the DropDownList. In this case you don't have to change the consturctor.

I don't really have a way to test this...but your code would look something like:
Expand|Select|Wrap|Line Numbers
  1.     void ddl_DataBinding(object sender, EventArgs e)
  2.     {
  3.         DropDownList ddd = (DropDownList)sender;
  4.         GridViewRow container = (GridViewRow)ddd.NamingContainer;
  5.  
  6.      GridView gv = (GridView)container.NamingContainer;
  7.      int rowCount = gv.Rows.Count;
  8.      ddd.ID = "dropdownlist" & rowCount.ToString();
  9.  
  10.         object dataValue = DataBinder.Eval(container.DataItem, _columnName);
  11.         if (dataValue != DBNull.Value)
  12.         {
  13.             ddd.Text = dataValue.ToString();
  14.         }
  15.     }
In your button click event you need to retrieve the GridViewRow that you want to use and call the FindControl method for each DropDownList on it like this:
Expand|Select|Wrap|Line Numbers
  1. List<DropDownList> ddlListsForRow1;
  2. ddlListsForRow1= new List<DropDownList>();
  3.  
  4. int dropDownListIteration;
  5.  
  6. for(dropDownListIteration=0; dropDownListIteration<numOfDropDownLists; i++)
  7. {
  8.   DropDownList ddl = (DropDownList))grdMatrix.Rows[1].FindControl("dropdownlist" & dropDownListIteration);
  9.   ddlListsForRow1.Add(ddl);
  10. }
  11.  
-Frinny
Aug 31 '10 #4
sasha3
6
Thank you very much for your detailed answer, i try now to implement this. Also found a nice, article,
http://www.singingeels.com/Articles/...in_ASPNET.aspx
Sep 1 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: hb | last post by:
Hi, I have a page bill.aspx and its code-behind bill.aspx.cs. On bill.aspx I have: === Select a month: <asp:dropdownlist runat="server" id="lstDate" autopostback="True" /> <br> <asp:table...
1
by: Chen Sun via .NET 247 | last post by:
I have posted this message 15 hours ago but I still could not seeit. So I decide repost it. I have successully used Jeffrey Ton's method to generate dymanicTextBox. Now my problem is that After...
2
by: vikram | last post by:
I have to design a page which contains a dynamic generated menu at left side.Menu will be generated once a user log in and will remain as it is for the rest of the user session. Problem is that...
5
by: alingsjtu | last post by:
Hello, every body. When execute dynamic generated multiple OPENQUERY statements (which linkes to DB2) in SQLServer, I always got SQL1040N The maximum number of applications is already connected...
1
by: aekta | last post by:
Hello all, How we get The Value of Dynamic generate TextBox in asp.net? i have a web form and in which i want to create textbox dynamically by click on Button ...Now,on another button click I...
0
geo039
by: geo039 | last post by:
I have a usercontrol with textboxes. Most of which refer to a gridview on selection. A user clicks a looking glass and a gridview appears to select items (like a dropdown). The page loads with...
2
by: mylog | last post by:
Hi all, I am having a small problem on getting the values of the dynamically generated textboxes in C# windows application. I have successfully read an xml file and put its key and value fields as...
1
by: adepvivek | last post by:
Hi everybody, I am using textbox in gridview as template. And I want to stored the value of textbox. For that I want to pass the textbox value to stored procedure. So please give me solution.
0
by: Venkata Krishnam Raju | last post by:
Unable to find the Textbox in Gridview which Template controls created dynamically
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.