I am attempting to access user enter data in dynamic controls in asp.net.
I am not creating the controls in page_load because they exist based on a sql query that is only resolved after the user selects a value from a drop down list.
I have the ids generated so they are consistent and a submit button which refreshes, also I am using ajax update panels. What I am lacking is any code for actually saving the state of the dynamic controls before postback and naturally by the page load point they do not exist yet.
What do I need to do to make sure the controls values carry over?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadDD1();
}
}
private void loadDD1()
{
try
{
ListItemCollection lic = DataAccessHelper.stNumsForName(ddaddressname.SelectedValue.ToString());
ddaddressnumber.DataSource = lic;
ddaddressnumber.DataTextField = "Text";
ddaddressnumber.DataValueField = "Value";
ddaddressnumber.DataBind();
if (tbaddaddressnumber.Text != "")
{
ddaddressnumber.SelectedValue = tbaddaddressnumber.Text;
tbaddaddressnumber.Text = null;
}
}
catch (Exception es)
{
}
}
protected void btret_Click(object sender, EventArgs e)
{
loadAll(); // Once a value from dropdown is selected
}
private void loadAll()
{
int FDDkey = int.Parse(ddaddressnumber.Items[ddaddressnumber.SelectedIndex].Value);
BusinessObjects.ResidenceFDD res = new BusinessObjects.ResidenceFDD();
try
{
AnnArborFDDModel.AnnArborFDDEntities1 com = new AnnArborFDDModel.AnnArborFDDEntities1();
// Communication com = new Communication();
var query = from a in com.Communications
where a.fddkey == res.FDDKey
select a;
var querydd = (from b in com.Communications
where !String.IsNullOrEmpty(b.subject)
select b.subject).Distinct();
var collectiondetails = new List<object>();
// collectiondetails.Add(querydd);
TextBox notestbbase = new TextBox();
DropDownList notesddbase = new DropDownList();
TextBox notestbcomments = new TextBox();
TableRow tr01 = new TableRow();
tr01.Cells.Add(new TableCell());
tr01.Cells.Add(new TableCell());
tr01.Cells[0].Text = "Date:";
tr01.Cells[1].Text = "Correspondent:";
this.tblnotes.Rows.Add(tr01);
TableRow tr02 = new TableRow(); // Not sure if new row needs to be instantiated or not.
tr02.Cells.Add(new TableCell());
tr02.Cells.Add(new TableCell());
notestbbase.ID = "notestbbase";
tr02.Cells[0].Controls.Add(notestbbase);
notesddbase.ID = "notesddbase";
notesddbase.DataSource = querydd.ToList();
notesddbase.DataBind();
notesddbase.Items.Insert(0, emptyItem);
notesddbase.SelectedIndex = 0;
tr02.Cells[1].Controls.Add(notesddbase);
this.tblnotes.Rows.Add(tr02);
TableRow tr03 = new TableRow(); // Not sure if new row needs to be instantiated or not.
tr03.Cells.Add(new TableCell());
notestbcomments = new TextBox();
notestbcomments.ID = "notestbcomments";
notestbcomments.Width = 150;
notestbcomments.Height = 150;
notestbcomments.Wrap = true;
notestbcomments.TextMode = TextBoxMode.MultiLine;
tr03.Cells[0].Controls.Add(notestbcomments);
this.tblnotes.Rows.Add(tr03);
}
catch (Exception ex)
{}
}
protected void btupdate_Click(object sender, EventArgs e)
{
try
{
Dictionary<string, string> idAndValueDictionary = new Dictionary<string, string>();
TextBox tbdatetoadd = (TextBox)FindControl("notestbbase"); //Communications table
DropDownList ddcorrespondanttoadd = (DropDownList)FindControl("notesddbase"); // Communications table
TextBox tbnotestoadd = (TextBox)FindControl("notestbcomments");
}
// There is a catch statement here I am trying not to spam with too much code.
}
Try this, I have not tested this...
Dictionary<string, string> idAndValueDictionary = new Dictionary<string, string>();
Fill the dictionary and when you save the data to viewstate.
idAndValueDictonary.Add(control id, value); // in a loop
ViewState["idAndValueDictionary"] = idAndValueDictionary;
and on postback:
idAndValueDictionary = ViewState["idAndValueDictionary"] as Dictionary<string, string>;
Then loop through, setting the values based on the id's accordingly.
Related
I have to show a ModalPopupExtender when changing the items of dropdownlist. The controls showing inside the ModalPopupExtender are dynamic controls including buttons. To fire the button click event for this dynamic buttons, I have introduced view state in the code.
Now when changing the item of dropdown list, ModalPopupExtender will come for first item correctly. And then, when changing the item, it throws error like below. How can I clear the previous dynamic controls when changing the dropdown list items?
Multiple controls with the same ID 'lbl1' were found. FindControl requires that controls have unique IDs.
protected async void Page_Load(object sender, EventArgs e)
{
if (ddl_Forms.SelectedItem.Value != "-1")
if (ViewState["viewstate_dynamic"] != null)
CreateDynamicControls();
}
protected void ddl_Forms_SelectedIndexChanged(object sender, EventArgs e)
{
CreateDynamicControls();
}
private async void CreateDynamicControls()
{
if (ddl_Forms.SelectedItem.Value != "-1")
{
url = baseUrl + "GetStructureJson?form_id=" + ddl_Forms.SelectedItem.Value.ToString();
using (var objClient = new HttpClient())
{
objClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + objVariables.login_token);
using (var response = await objClient.GetAsync(url))
{
if ((int)response.StatusCode == 401)//unauthorised or token expired
{
Response.Redirect("Default.aspx");
}
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
JavaScriptSerializer j = new JavaScriptSerializer();
object a = j.Deserialize(jsonString, typeof(object));
dict_values = JsonConvert.DeserializeObject<Dictionary<string, string>>(a.ToString());
int flag = 0;
foreach (KeyValuePair<string, string> entry in dict_values)
{
flag++;
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
Label lbl = new Label();
lbl.ID = "lbl" + flag;
lbl.Text = entry.Key;
cell1.Controls.Add(lbl);
row.Cells.Add(cell1);
tbl_forms.Rows.Add(row);
}
TableRow row3 = new TableRow();
TableCell cell3 = new TableCell();
Button btn = new Button();
btn.ID = "btnSubmit2";
btn.Text = "Submit";
btn.Click += new System.EventHandler(this.ButtonsubmitForm2_Click);
btn.CssClass = "button_green";
cell3.Controls.Add(btn);
Button btn2 = new Button();
btn2.ID = "btnCancel2";
btn2.Text = "Cancel";
btn2.Click += new EventHandler(btn_Cancel_allocate2_Click);
btn2.Style.Add("margin-left", "20px");
cell3.Controls.Add(btn2);
row3.Cells.Add(cell3);
tbl_forms.Rows.Add(row3);
**ViewState.Add("viewstate_dynamic", true);**
mp2.Show(); //modalpopuextender
}
}
}
}
}
public partial class Questions : System.Web.UI.Page
{
private bool InstanceFieldsInitialized = false;
private Questions()
{
if (!InstanceFieldsInitialized)
{
InitializeInstanceFields();
InstanceFieldsInitialized = true;
}
}
private void InitializeInstanceFields()
{
r = User.Identity.Name;
}
private ArrayList #params = new ArrayList();
string r;
private ArrayList pklist = new ArrayList();
//Dynamically Loads the Questions based off of the table.
protected void Page_Load(object sender, System.EventArgs e)
{
//Questions Loaded
string proc = "Question_Select";
SqlConnection QuestionsConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand QuestionsCommand = new SqlCommand(proc, QuestionsConnection);
QuestionsCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(QuestionsCommand);
DataTable vTable = new DataTable();
da.Fill(vTable);
Table detailsTable = new Table();
detailsTable.CellSpacing = 10;
var i = 0;
foreach (DataRow row in vTable.Rows)
{
var value = vTable.Rows[i][0].ToString();
TableRow tRow = new TableRow();
TableCell tCell1 = new TableCell();
TableCell tCell2 = new TableCell();
var pk = vTable.Rows[i][1].ToString();
pklist.add(pk);
Label myLabel = new Label();
myLabel.CssClass = "bold";
TextBox myText = new TextBox();
myText.TextMode = TextBoxMode.MultiLine;
myText.Columns = 40;
myText.Rows = 4;
myText.ID = "Box" + i;
#params.add(myText.ID);
myLabel.Text = string.Format("{0}. {1}", i + 1, value);
tCell1.Controls.Add(myLabel);
tCell2.Controls.Add(myText);
tRow.Cells.Add(tCell1);
tRow.Cells.Add(tCell2);
detailsTable.Rows.Add(tRow);
i += 1;
}
Panel1.Controls.Add(detailsTable);
}
//INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
//ORIGINAL LINE: Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
protected void Button1_Click(object sender, EventArgs e)
{
//When a survey is completed, this method checks to see who completed the survey and insert them into a table.
string proc2 = "User_Insert";
SqlConnection ResponsesConnection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand ResponsesCommand2 = new SqlCommand(proc2, ResponsesConnection2);
ResponsesCommand2.CommandType = CommandType.StoredProcedure;
ResponsesCommand2.Parameters.AddWithValue("#UserName", r);
ResponsesConnection2.Open();
ResponsesConnection2 = (SqlConnection)ResponsesCommand2.ExecuteScalar();
// Establish connection and set up command to use stored procedure
string proc = "Responses_Insert";
SqlConnection ResponsesConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Feedback-ConnectionString"].ConnectionString);
SqlCommand ResponsesCommand = new SqlCommand(proc, ResponsesConnection);
ResponsesCommand.CommandType = CommandType.StoredProcedure;
ResponsesConnection.Open();
<--HERE IS WHERE I THINK THE PROBLEM IS-->
***var i = 0;
for (int a = 0; a < #params.ToString().Count(); a++)
{
ResponsesCommand.Parameters.Clear();
TextBox textbox = Panel1.FindControl(#params.ToString().ElementAt(a).ToString()) as TextBox;
ResponsesCommand.Parameters.AddWithValue("#QuestionID", pklist.ToString().ElementAt(i).ToString());
ResponsesCommand.Parameters.AddWithValue("#response", textbox.Text);
ResponsesCommand.Parameters.AddWithValue("#UserName", r);
ResponsesConnection = (SqlConnection)ResponsesCommand.ExecuteScalar();
i += 1;***
}
Microsoft.VisualBasic.Interaction.MsgBox("Thank you for completing the survey.", Microsoft.VisualBasic.MsgBoxStyle.MsgBoxSetForeground, "Survey Complete");
Response.Redirect("../../../Default.aspx");
}
//Button to see if a person has chosen to be marked annonymous.
//INSTANT C# WARNING: Strict 'Handles' conversion only applies to fields declared in the same class - the event will be wired in 'SubscribeToEvents':
//ORIGINAL LINE: Protected Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles Checkbox1.CheckedChanged
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (Checkbox1.Checked == false)
{
r = User.Identity.Name;
}
else
{
r = "Anonymous";
}
}
}
}
I need a little help. My code shows double output when ran. Had multiple choices to use var, object, or dynamic using code converters. Chose var but it still outputs double. When debugger is ran shows no errors.
I would question whether you need .ToString() in the following (in the for loop):
a < #params.ToString().Count()
It seems like you probably just want the number of items in the #params list, so try replacing the above with the following:
a < #params.Count
That may fix your problem of the loop executing the wrong number of times. If so, then similarly within the loop body you probably shouldn't be using .ToString() in either of these:
#params.ToString().ElementAt(a)
pklist.ToString().ElementAt(i)
If your loop still seems to be executing too many times, then you should try stepping through it in the debugger or adding print statements (Console.WriteLine) to print the variable values for each iteration of the loop and better understand what it's doing.
Everything should work, but i can't figure out why i can't get the value from the ddl. I know the code is not too clean.
protected void gridProduse_RowEditing(object sender, GridViewEditEventArgs e)
{
gridProduse.EditIndex = e.NewEditIndex;
gridProduse.DataBind();
using (var context = new SATContext())
{
var query = from t in context.TipuriProduse
select t.Denumire;
DropDownList list = new DropDownList();
list.DataSource = query.ToList();
list.DataBind();
list.ID = "ddlTipProdus";
list.Height = 27;
DropDownList listMoneda = new DropDownList();
listMoneda.ID = "ddlMoneda";
listMoneda.Items.Add("RON");
listMoneda.Items.Add("EUR");
listMoneda.Items.Add("USD");
listMoneda.Height = 27;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls.Add(list);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls.Add(listMoneda);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls[0].Visible = false;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls[0].Visible = false;
}
}
protected void gridProduse_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridProduse.Rows[e.RowIndex];
Produs prod = new Produs();
prod.ProdusId = Convert.ToInt32(((TextBox)(row.Cells[2].Controls[0])).Text);
prod.Denumire = ((TextBox)(row.Cells[3].Controls[0])).Text;
DropDownList ddl = (DropDownList)gridProduse.Rows[e.RowIndex].FindControl("ddlMoneda");
prod.Moneda = ddl.SelectedValue; // this is where i get the error
//prod.Moneda = ((row.FindControl("ddlMoneda") as DropDownList)).SelectedValue;
prod.PretCuTVA = Convert.ToInt32(((TextBox)(row.Cells[5].Controls[0])).Text);
prod.PretFaraTVA = Convert.ToInt32 (((TextBox)(row.Cells[4].Controls[0])).Text);
lit1.Text = prod.ProdusId.ToString();
using (var context = new SATContext())
{
IRepository<Produs> ProdusRepository = new ProdusRepository();
ProdusRepository.Update(prod);
}
gridProduse.EditIndex = -1;
gridProduse.DataBind();
Response.Redirect("Produse.aspx");
}
And this is the error:
An exception of type 'System.NullReferenceException' occurred in Licenta.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
I'm pretty sure that you need to select a cell before you can reliably call `FindControl'
(DropDownList)gridProduse.Rows[e.RowIndex].Cells[SomeCell].FindControl("ddlMoneda");
Since your listMoneda control is being created dynamically after the Page_Init event, it is not being registered in the ViewState, and thus cannot be found on PostBack. Read this explanation for a solution
I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.
I'm adding dropdownlists to my page depending on a amount of database entries and when I press the button I want to get the selected values in each dropdownlist.
I tried this
foreach(DropDownList a in Form.Controls.OfType<DropDownList>())
{
Response.Write(a.SelectedValue);
}
but it doesn't find any dropdownlist on the page. Below is the code I use to add the dorpdownlists.
protected void Page_Init()
{
string product = Request.QueryString["product"];
foreach (productoption r in dbcon.GetOption(product))
{
TableRow row = new TableRow();
TableCell cel1 = new TableCell();
TableCell cel2 = new TableCell();
DropDownList dropdown1 = new DropDownList();
dropdown1.CssClass = "productdropdown";
foreach (suboption f in dbcon.GetSubOption(r.ProductOptionID))
{
dropdown1.Items.Add(f.SubOptionName + " +$" +f.SubOptionPrice);
}
cel1.Text = "<b>" + r.OptionName + "</b>";
cel2.Controls.Add(dropdown1);
row.Cells.Add(cel1);
row.Cells.Add(cel2);
Table1.Rows.Add(row);
}
TableRow row2 = new TableRow();
TableCell cell3 = new TableCell();
Button cartbutton = new Button();
cartbutton.ID = product;
cartbutton.CssClass = "btn_addcart";
cartbutton.Click += cartbutton_OnClick;
cartbutton.Text = "Add to cart";
cell3.Controls.Add(cartbutton);
row2.Cells.Add(cell3);
Table1.Rows.Add(row2);
}
foreach (TabelRow row in Table1.Rows)
{
if(row.Cells.Count > 0)
{
if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0].GetType() == typeof(DropDownList))
{
Response.Write(a.SelectedValue);
}
}
}
First you should make a function that looks for a control type in a ControlCollection and returns a list of found controls. Something like that:
public List<T> GetControlsOfType<T>(ControlCollection controls)
{
List<T> ret = new List<T>();
try
{
foreach (Control control in controls)
{
if (control is T)
ret.Add((T)((object)control));
else if (control.Controls.Count > 0)
ret.AddRange(GetControlsOfType<T>(control.Controls));
}
}
catch (Exception ex)
{
//Log the exception
}
return ret;
}
and then you can get all DropDownList like that:
List<DropDownList> ret = GetControlsOfType<DropDownList>(this.Page.Controls);
I hope it helped.
You should be adding controls inside another control for example a panel
*Also you dont need to define controls at page init, you can do that at page load and they will retain their value*
protected void Page_Load(object sender, EventArgs e)
{
loadControls();
}
//For Instance lets take a dropdownlist and add it to a panel named testpanel
Protected void loadControls()
{
DropdownList ddlDynamic = new DropdownList();
//give this control an id
ddlDynamic.Id = "ddlDynamic1"; // this id is very important as the control can be found with same id
//add data to dropdownlist
//adding to the panel
testpanel.Controls.Add(ddlDynamic);
}
//Now we have to find this control on post back for instance a button click
protected void btnPreviousSet_Click(object sender, EventArgs e)
{
//this will find the control here
//we will you the same id used while creating control
DropdownList ddlDynamic1 = testpanel.FindControl("ddlDynamic1") as DropdownList;
//can resume your operation here
}