NullReferenceException Controls.Add c# error - c#

I'm getting the following error after I start debugging my program. Do you know how to fix this?
System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object."
It is referring to the line:
pnlDropDownList.Controls.Add(ddl);
inside the CreateDropDownLists method. Apparently the ddl must be a null object, even though I initialized ddl just before in this same method. Do you understand why I am receiving this error? See code below...
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADONET_namespace;
using MatrixApp;
namespace AddFileToSQL
{
public partial class DataMatch : _Default
{
protected System.Web.UI.WebControls.PlaceHolder phTextBoxes;
protected System.Web.UI.WebControls.PlaceHolder phDropDownLists;
protected System.Web.UI.WebControls.Button btnAnotherRequest;
protected System.Web.UI.WebControls.Panel pnlCreateData;
protected System.Web.UI.WebControls.Literal lTextData;
protected System.Web.UI.WebControls.Panel pnlDisplayData;
Panel pnlDropDownList;
protected static string inputfile2;
static string[] headers = null;
static string[] data = null;
static string[] data2 = null;
static DataTable myInputFile = new DataTable("MyInputFile");
static string[] myUserSelections;
// a Property that manages a counter stored in ViewState
protected int NumberOfControls
{
get { return (int)ViewState["NumControls"]; }
set { ViewState["NumControls"] = value; }
}
public void EditRecord(object recordID)
{
SelectedRecordID = recordID;
// Load record from database and show in control
}
protected object SelectedRecordID
{
get
{
return ViewState["SelectedRecordID"];
}
set
{
ViewState["SelectedRecordID"] = value;
}
}
protected void OnPreLoad(object sender, EventArgs e)
{
//Create a Dynamic Panel
pnlDropDownList = new Panel();
pnlDropDownList.ID = "pnlDropDownList";
pnlDropDownList.BorderWidth = 1;
pnlDropDownList.Width = 300;
this.form1.Controls.Add(pnlDropDownList);
}
// Page Load
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
this.NumberOfControls = 0;
}
}
// Add DropDownList Control to Placeholder
private void CreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID" + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(this.OnSelectedIndexChanged);
pnlDropDownList.Controls.Add(ddl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
dr.Close();
}
}
private void CreateLabels()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
Label lbl = new Label();
lbl.ID = "Label" + counter.ToString();
lbl.Text = headers[counter];
lbl.Style["position"] = "absolute";
lbl.Style["top"] = 100 * counter + 50 + "px";
lbl.Style["left"] = 250 + "px";
pnlDropDownList.Controls.Add(lbl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Add TextBoxes Control to Placeholder
private void RecreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID" + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
myUserSelections[counter] = "";
dr.Close();
ddl.AutoPostBack = true;
ddl.EnableViewState = false; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
pnlDropDownList.Controls.Add(ddl);
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Create TextBoxes and DropDownList data here on postback.
protected override void CreateChildControls()
{
// create the child controls if the server control does not contains child controls
this.EnsureChildControls();
// Creates a new ControlCollection.
this.CreateControlCollection();
// Here we are recreating controls to persist the ViewState on every post back
if (Page.IsPostBack)
{
RecreateDropDownLists();
RecreateLabels();
}
// Create these conrols when asp.net page is created
else
{
PopulateFileInputTable();
CreateDropDownLists();
CreateLabels();
}
// Prevent child controls from being created again.
this.ChildControlsCreated = true;
}
private void AppendRecords()
{
switch (targettable)
{
case "ContactType":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataCT(myInputFile.Rows[r]); }
break;
case "Contact":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataC(myInputFile.Rows[r]); }
break;
case "AddressType":
for (int r = 0; r < myInputFile.Rows.Count; r++)
{ ADONET_methods.AppendDataAT(myInputFile.Rows[r]); }
break;
default: throw new ArgumentOutOfRangeException("targettable type", targettable);
}
}
// Read all the data from TextBoxes and DropDownLists
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
int cnt = FindOccurence("DropDownListID");
EditRecord("DropDownListID" + Convert.ToString(cnt + 1));
AppendRecords();
pnlDisplayData.Visible = false;
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
(this.btnSubmit_Click);
}
#endregion
}
}

I think it's referring to "pnlDropDownList" being a Null object. That function must be getting called before "pnlDropDownList = new Panel();" in "OnPreLoad". Use breakpoints to step through the source and follow the code-path. I'm sure you'll find this is the case.

You might want to try creating your dynamic controls in PreInit, I have a hunch that the Panel has not yet been initialized and hence the exception
Check out the Page Lifecycle

Related

dynamically place controls in datagrid according to condition

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.

how I save dynamically created Labels and Checkboxes values into sql server

how I save dynamically created Labels and Checkboxes values into sql server
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into Event(EventName,StartDate,EventDuration,StartTime,EndTime,SlotDuration) output inserted.EventId values(#EventName,#StartDate,#EventDuration,#StartTime,#EndTime,#SlotDuration)", con);
cmd1.Parameters.AddWithValue("#EventName", EventName_TB.Text);
cmd1.Parameters.AddWithValue("#StartDate", StartDate_TB.Text);
cmd1.Parameters.AddWithValue("#EventDuration", EventDuration_DDL.Text);
cmd1.Parameters.AddWithValue("#StartTime", StartTime_DDL.Text);
cmd1.Parameters.AddWithValue("#EndTime", EndTime_DDL.Text);
cmd1.Parameters.AddWithValue("#SlotDuration", SlotDuration_DDL.Text);
Int32 id = (Int32)cmd1.ExecuteScalar();
var label = Labeldiv.FindControl("Label1") as Label;
var checkbox = Labeldiv.FindControl("CheckBox1") as CheckBox;
using (SqlCommand cmd2 = new SqlCommand("insert into EventDays(EventDay,EventStatus)values(#EventDay,#EventStatus)", con))
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
var paramDay = cmd2.Parameters.Add("#EventDay", SqlDbType.DateTime);
var paramStatus = cmd2.Parameters.Add("#EventStatus", SqlDbType.Int);
paramDay.Value = label.Text;
paramStatus.Value = checkbox.Checked ? 1 : 0;
cmd2.ExecuteNonQuery();
}
}
con.Close();
}
I have created Labels and CheckBoxes dynamically in EventDuration_DDL_SelectedIndexChanged.
now I want to save these values into sql server in Wizard1_FinishButtonClick.
how I save dynamically created Labels and Checkboxes values into sql server
.
.
.
.
..
You have to recreate those dynamically created labels and check boxes for the button click as well, because when the user clicks the finish button, that causes a post back to the server and the page is recreated, but the dynamic label and check box logic is not executed, thus your database saving logic cannot "find" these controls.
I recommend moving your dynamic label and check box creation logic to a separate method that can be called by the EventDuration_DDL_SelectedIndexChanged() and Wizard1_FinishButtonClick(), like this:
private void BuildDynamicControls()
{
int n = Int32.Parse(EventDuration_DDL.SelectedItem.ToString());
for (int i = 0; i < n; i++)
{
Label NewLabel = new Label();
NewLabel.ID = "Label" + i;
var eventDate = Calendar1.SelectedDate.Date.AddDays(i);
NewLabel.Text = eventDate.ToLongDateString();
CheckBox newcheck = new CheckBox();
newcheck.ID = "CheckBox" + i;
this.Labeldiv.Controls.Add(new LiteralControl("<span class='h1size'>"));
this.Labeldiv.Controls.Add(NewLabel);
this.Labeldiv.Controls.Add(new LiteralControl("</span>"));
this.Labeldiv.Controls.Add(new LiteralControl("<div class='make-switch pull-right' data-on='info'>"));
this.Labeldiv.Controls.Add(newcheck);
this.Labeldiv.Controls.Add(new LiteralControl("</div>"));
this.Labeldiv.Controls.Add(new LiteralControl("<br/>"));
}
}
Now in your event handlers, you can call this method, like this:
protected void EventDuration_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
BuildDynamicControls();
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
BuildDynamicControls();
}
Alternatively, you can call BuildDynamicControls() in the Page_Load. This takes care of other buttons on the page destroying the values when they cause a post back, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Do other page load logic here
BuildDynamicControls();
}
Note: If you go this route, then you will not need to call BuildDynamicControls() in the EventDuration_DDL_SelectedIndexChanged() or Wizard1_FinishButtonClick() methods, because the Page_Load happens before either of those events in the page life-cycle.

Dynamic textfields does not retain data on postback

I created a webform that allows the user to dynamically add more textboxes. Right now, as the button is clicked to add another field, it postbacks to itself. The controls are added in the Pre_Init. However when the page reconstructs itself the textbox names are different each time so the data is not being retained on each postback.
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
I have tried this solution How can I get data from dynamic generated controls in ASP .NET MVC?

DevExpress: ASPxGridView GroupBy() won't work

My goal is to group the data at runtime inside a grdView which added to a panel also at runtime
grdView.DataSource = tbl;
grdView.DataBind();
grdView.Settings.ShowGroupPanel = true;
grdView.BeginUpdate();
grdView.GroupBy((DevExpress.Web.ASPxGridView.GridViewDataColumn) grdView.Columns["ClmnName"]);//or an index (0) for example
grdView.EndUpdate();
any suggestions?
EDIT:
Current Code
//GRID
pnlGrids.Controls.Add(grdView);
grdView.DataSource = tbl;//Datasource
foreach (GridViewDataTextColumn clmn in grdView.Columns)//HTML
clmn.PropertiesTextEdit.EncodeHtml = false;
if (key.GroupingDataMembers.Any())//Group panel
grdView.Settings.ShowGroupPanel = true;
grdView.Images.ImageFolder = "~/App_Themes/Aqua/GridView/";//Style
grdView.Styles.CssFilePath = "~/App_Themes/Aqua/GridView/styles.css";
grdView.Styles.CssPostfix = "Aqua";
grdView.DataBind();//Bind
if (key.GroupingDataMembers.Any())//Grouping
(grdView.Columns[key.GroupingDataMembers.First().DataMember.DisplayName] as DevExpress.Web.ASPxGridView.GridViewDataColumn).GroupBy();
grdView.ExpandAll();//Expand all
The following code works fine here:
protected void Page_Load(object sender, EventArgs e) {
ASPxGridView grid = new ASPxGridView();
grid.ID = "grid";
pnl.Controls.Add(grid);
DataTable t = new DataTable();
t.Columns.Add("Id");
t.Columns.Add("Data");
for(int i = 0; i < 100; i++) {
t.Rows.Add(new object[] { i, "row " + i.ToString() });
}
grid.DataSource = t;
grid.Settings.ShowGroupPanel = true;
grid.DataBind();
(grid.Columns["Data"] as GridViewDataColumn).GroupBy();
}

C# Hashtable does not retain values

I am using a hashtable to store key-value pairs and I initialize this hashtable (ddl_ht) in the method CreateDropDownLists(). However, when I check the value of "currentItem" in my SelectedIndexChanged method, this value is null. Even though I checked the value of
(string)ddl_ht[key[1]]
in my Watch window and it shows a value (not null). Do you understand why this currentItem is null?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADONET_namespace;
namespace AddFileToSQL
{
public partial class DataMatch : _Default
{
protected System.Web.UI.WebControls.PlaceHolder phTextBoxes;
protected System.Web.UI.WebControls.PlaceHolder phDropDownLists;
protected System.Web.UI.WebControls.Button btnAnotherRequest;
protected System.Web.UI.WebControls.Panel pnlCreateData;
protected System.Web.UI.WebControls.Literal lTextData;
protected System.Web.UI.WebControls.Panel pnlDisplayData;
protected static string inputfile2;
static string[] headers = null;
static string[] data = null;
static string[] data2 = null;
static DataTable myInputFile = new DataTable("MyInputFile");
static string[] myUserSelections;
static Hashtable ddl_ht = new Hashtable();
// Page Load
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
this.NumberOfControls = 0;
}
}
// Add DropDownList Control to Placeholder
private void CreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID " + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
//myUserSelections[counter] = "";
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
ddl_ht.Add(counter, ddl.SelectedValue);
pnlDisplayData.Controls.Add(ddl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
pnlDisplayData.Visible = true;
pnlDisplayData.FindControl(ddl.ID);
// pnlDropDownList.FindControl(ddl.ID);
dr.Close();
}
}
protected void SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
string[] value=(ddl.SelectedValue).Split(' ');
string[] key = ddl.ID.Split(' ');
string currentItem=(string)ddl_ht[key[1]];
//if (String.IsNullOrEmpty(currentItem))
//{
// ddl_ht.Add(key[1], value[0]);
//}
if (currentItem != ddl.SelectedValue)
{
ddl_ht.Remove(key[1]);
ddl_ht.Add(key[1], ddl.SelectedValue);
}
}
// Add TextBoxes Control to Placeholder
private void RecreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID " + (counter + 1).ToString();
ddl.DataTextField = "COLUMN_NAME";
ddl.DataValueField = "COLUMN_NAME";
ddl.DataSource = dr;
ddl.DataBind();
myUserSelections[counter] = "";
dr.Close();
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
ddl.Style["position"] = "absolute";
ddl.Style["top"] = 100 * counter + 80 + "px";
ddl.Style["left"] = 250 + "px";
ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged);
pnlDisplayData.Controls.Add(ddl);
pnlDisplayData.Controls.Add(new LiteralControl("<br><br><br>"));
}
}
// Create TextBoxes and DropDownList data here on postback.
protected override void CreateChildControls()
{
// create the child controls if the server control does not contains child controls
this.EnsureChildControls();
// Creates a new ControlCollection.
this.CreateControlCollection();
// Here we are recreating controls to persist the ViewState on every post back
if (Page.IsPostBack)
{
RecreateDropDownLists();
RecreateLabels();
}
// Create these conrols when asp.net page is created
else
{
PopulateFileInputTable();
CreateDropDownLists();
CreateLabels();
}
// Prevent child controls from being created again.
this.ChildControlsCreated = true;
}
}
}
You are going to have all kinds of threading problems with this setup. Your hashtable is static, and every hit on your website is going to create a new instance of your class on a new thread that will try to access the same hashtable - and since each new hit to the page will initially call CreateDropDownLists, your hashtable will be reinitialzed for every new user to the page.
You shouldn't store your HashTable as a static field of your page class, since it will be shared between sessions because the life cycle of a static variables in ASP.NET is within the life of the appdomain, consider storing it in the ViewState:
private Hashtable ddl_ht
{
get
{
return ViewState["ddl_ht"] as HashTable;
}
set
{
ViewState["ddl_ht"] = value;
}
}

Categories

Resources