I have to dynamically create controls and add them to a table. In a button click I need to find the value entered for that control. The control ids are also dynamic. Below is the code I tried.
private void createUdfControls()
{
colUdfNames.Clear();//this is a collection object.
//the from id for gl is 3.
colUdfNames = BL_GeneralLedger.GetAllUdfNames(3);
if (colUdfNames.Count>0)
{
TableRow tr1 = null; ;
for(int i=0;i<colUdfNames.Count;i++)
{
TableRow tr;
if(i%2==0)
{
tr = new TableRow();
tr1 = tr;
}
string udfTypeValue = colUdfNames[i].UdfTypeValue;
int EnumUdfTypeId = colUdfNames[i].Enum_UdfTypeId;
TableCell cellUdf1 = new TableCell();
TableCell cellUdfValue1 = new TableCell();
TableCell cellUdf2 = new TableCell();
TableCell cellUdfValue2 = new TableCell();
switch (EnumUdfTypeId)
{
case 1:
{
//Text
if (i % 2 == 0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtText = new TextBox();
txtText.ID = "txtText" + colUdfNames[i].UdfId;
txtText.MaxLength = colUdfNames[i].Width;
txtText.Text = "ww";
cellUdfValue1.Controls.Add(txtText);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtText = new TextBox();
txtText.ID = "txtText" + colUdfNames[i].UdfId;
txtText.MaxLength = colUdfNames[i].Width;
txtText.Text = "ww";
cellUdfValue2.Controls.Add(txtText);
}
break;
}
case 2:
{
//Number
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtNumber = new TextBox();
txtNumber.ID = "txtNumber" + colUdfNames[i].UdfId;
txtNumber.MaxLength = colUdfNames[i].Width;
txtNumber.Text = "12";
cellUdfValue1.Controls.Add(txtNumber);
DataRow dr = dtUdfControlInfo.NewRow();
dr[0] = txtNumber.ID;
dtUdfControlInfo.Rows.Add(dr);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtNumber = new TextBox();
txtNumber.ID = "txtNumber" + colUdfNames[i].UdfId;
txtNumber.MaxLength = colUdfNames[i].Width;
txtNumber.Text = "12";
cellUdfValue2.Controls.Add(txtNumber);
DataRow dr = dtUdfControlInfo.NewRow();
dr[0] = txtNumber.ID;
dtUdfControlInfo.Rows.Add(dr);
}
break;
}
case 3:
{
//Decimal
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtDecimal = new TextBox();
txtDecimal.ID = "txtDecimal" + colUdfNames[i].UdfId;
txtDecimal.MaxLength = colUdfNames[i].Width;
txtDecimal.Text = "2.2";
cellUdfValue1.Controls.Add(txtDecimal);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtDecimal = new TextBox();
txtDecimal.ID = "txtDecimal" + colUdfNames[i].UdfId;
txtDecimal.MaxLength = colUdfNames[i].Width;
txtDecimal.Text = "2.2";
cellUdfValue2.Controls.Add(txtDecimal);
}
break;
}
case 4:
{
//Memo
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtMemo = new TextBox();
txtMemo.TextMode = TextBoxMode.MultiLine;
txtMemo.ID = "txtMemo" + colUdfNames[i].UdfId;
txtMemo.MaxLength = colUdfNames[i].Width;
txtMemo.Text = "memo";
cellUdfValue1.Controls.Add(txtMemo);
DataRow dr = dtUdfControlInfo.NewRow();
dr[0] = txtMemo.ID;
dtUdfControlInfo.Rows.Add(dr);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtMemo = new TextBox();
txtMemo.TextMode = TextBoxMode.MultiLine;
txtMemo.ID = "txtMemo" + colUdfNames[i].UdfId;
txtMemo.MaxLength = colUdfNames[i].Width;
txtMemo.Text = "memo";
cellUdfValue2.Controls.Add(txtMemo);
DataRow dr = dtUdfControlInfo.NewRow();
dr[0] = txtMemo.ID;
dtUdfControlInfo.Rows.Add(dr);
}
break;
}
case 5:
{
//date
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtDate = new TextBox();
txtDate.ID = "txtDate" + colUdfNames[i].UdfId;
txtDate.MaxLength = colUdfNames[i].Width;
txtDate.Text = "12.07.2010";
cellUdfValue1.Controls.Add(txtDate);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtDate = new TextBox();
txtDate.ID = "txtDate" + colUdfNames[i].UdfId;
txtDate.MaxLength = colUdfNames[i].Width;
txtDate.Text = "12.07.2010";
cellUdfValue2.Controls.Add(txtDate);
}
break;
}
case 6:
{
//Datetime
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
TextBox txtDateTime = new TextBox();
txtDateTime.ID = "txtDateTime" + colUdfNames[i].UdfId;
txtDateTime.MaxLength = colUdfNames[i].Width;
txtDateTime.Text = "12.07.2010";
cellUdfValue1.Controls.Add(txtDateTime);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
TextBox txtDateTime = new TextBox();
txtDateTime.ID = "txtDateTime" + colUdfNames[i].UdfId;
txtDateTime.MaxLength = colUdfNames[i].Width;
txtDateTime.Text = "12.07.2010";
cellUdfValue2.Controls.Add(txtDateTime);
}
break;
}
case 7:
{
//"Dropdown"
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
DropDownList ddlDropDown = new DropDownList();
ddlDropDown.ID = "ddlDropDown" + colUdfNames[i].UdfId;
cellUdfValue1.Controls.Add(ddlDropDown);
LoadUdfList(ddlDropDown, colUdfNames[i].UdfId);
if (colUdfNames[i].IsMandatory)
{
ddlDropDown.Items.Insert(0, new ListItem("Select " + colUdfNames[i].UdfName, "0", true));
}
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
DropDownList ddlDropDown = new DropDownList();
ddlDropDown.ID = "ddlDropDown" + colUdfNames[i].UdfId;
cellUdfValue2.Controls.Add(ddlDropDown);
LoadUdfList(ddlDropDown, colUdfNames[i].UdfId);
if (colUdfNames[i].IsMandatory)
{
ddlDropDown.Items.Insert(0, new ListItem("Select " + colUdfNames[i].UdfName, "0", true));
}
}
break;
}
case 8:
{
//"Checkbox"
if(i%2==0)
{
cellUdf1.Text = colUdfNames[i].UdfName;
CheckBox ChkBox = new CheckBox();
ChkBox.ID = "ChkBox" + colUdfNames[i].UdfId;
ChkBox.Checked = true;
cellUdfValue1.Controls.Add(ChkBox);
}
else
{
cellUdf2.Text = colUdfNames[i].UdfName;
CheckBox ChkBox = new CheckBox();
ChkBox.ID = "ChkBox" + colUdfNames[i].UdfId;
ChkBox.Checked = true;
cellUdfValue2.Controls.Add(ChkBox);
}
break;
}
}
if (i % 2 == 0)
{
tr1.Cells.AddAt(0, cellUdf1);
tr1.Cells.AddAt(1, cellUdfValue1);
}
else
{
tr1.Cells.AddAt(2, cellUdf2);
tr1.Cells.AddAt(3, cellUdfValue2);
}
tblUdf.Rows.Add(tr1);
// tblUdf.DataBind();
}
}
}
and the read function as below
private void readValuesFromUdfControls()
{
colUdfDataMaster.Clear();
int c= tblUdf.Controls.Count;
int tablrow= tblUdf.Rows.Count;
//TextBox tb1 = (TextBox)tblUdf.Rows[0].FindControl(dtUdfControlInfo.Rows[0][0].ToString());
//string tb1 = (string)Request.Form["ctl00_ContentPlaceHolder1_" + dtUdfControlInfo.Rows[0][0].ToString()];
for (int j = 0; j < tblUdf.Rows.Count;j++ )
{
for (int k = 0; k < tblUdf.Rows[j].Cells.Count;k++ )
{
Control ctrl = tblUdf.Rows[j].Cells[k].Controls[1];
for (int i = 0; i < colUdfNames.Count; i++)
{
PL_UdfDataMaster objUdfDataMaster = new PL_UdfDataMaster();
if (ctrl.ID.Contains("txtText"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("txtNumber"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("txtDecimal"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("txtMemo"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("txtDate"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("txtDateTime"))
{
TextBox tb = (TextBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = tb.Text;
}
else if (ctrl.ID.Contains("ddlDropDown"))
{
DropDownList ddl = (DropDownList)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = ddl.SelectedItem.Text;
}
else if (ctrl.ID.Contains("ChkBox"))
{
CheckBox chk = (CheckBox)ctrl;
objUdfDataMaster.UdfId = colUdfNames[i].UdfId;
objUdfDataMaster.MasterId = ErpSessions._GeneralLedgerId;
objUdfDataMaster.Enum_FormId = 3;
objUdfDataMaster.UdfData = chk.Checked == true ? "true" : "false";
}
colUdfDataMaster.Add(objUdfDataMaster);
}
}
}
}
the problem is that i m getting the rowcount=0 of the table tblUdf inside which i added the table rows and controls inside the table cells.
Any help how to get the control values of the dynamically added controls.
Thankx.
Mohak
You need to make sure that you add the controls again on postback before you read back the values.
To elaborate on Ben's answer, you need to override the CreateChildControls method and create your controls there. The docs for this method provide a handy example of doing what you're doing:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.createchildcontrols.aspx
Related
everybody,
I have been trying for days now to solve this problem with no success.
I have textboxes in table cells which are created dynamically upon button click. Three of these buttons will take a value, calculation method (% or Const Value) and the value to apply respectively. Below is the function which creates these TB's among other controls.
protected void btnAddService_Click(object sender, EventArgs e)
{
TableRow r = new TableRow();
TableCell c0 = new TableCell();
TableCell c1 = new TableCell();
TableCell c2 = new TableCell();
TableCell c3 = new TableCell();
TableCell c4 = new TableCell();
TableCell c5 = new TableCell(); // Management Fees (% or Const)
TableCell c6 = new TableCell(); // Management Fees Value
TableCell c7 = new TableCell(); // Remarks
service s = new service();
if (serCount == 0)
{
tblHeader.Visible = true;
}
// Add the Services DropDownList...
DropDownList ddlS = new DropDownList();
ddlS.ID = "ddlServices" + serCount;
ddlS.Items.Add("Management");
ddlS.Items.Add("MEP");
ddlS.Items.Add("Landscaping");
ddlS.Items.Add("Pest Control");
ddlServices.Add(ddlS);
ddlS.CssClass = "form-control";
ddlS.Width = Unit.Percentage(100);
c0.Controls.Add(ddlS);
c0.Width = Unit.Percentage(15);
s.serviceName = "Management";
// Add Subcontracted Checkbox...
CheckBox chkSubCont = new CheckBox();
chkSubCont.ID = "chkSubCont" + serCount;
chkSubContracted.Add(chkSubCont);
c1.Controls.Add(chkSubCont);
c1.Width = Unit.Percentage(5);
c1.HorizontalAlign = HorizontalAlign.Center;
s.subcontracted = false;
// Add Subcontracted Value...
TextBox txtSubContVal = new TextBox();
txtSubContVal.ID = "txtSubcontractVal" + serCount;
txtSubContVal.CssClass = "form-control";
txtSubContVal.Attributes.Add("placeholder", "0.000");
txtSubContVal.Style.Add("text-align", "right");
txtSubcontValue.Add(txtSubContVal);
c2.Controls.Add(txtSubContVal);
c2.Width = Unit.Percentage(10);
s.subcontValue = 0;
// Add Management Fees Type (% or Const)...
DropDownList ddlMFT = new DropDownList();
ddlMFT.Items.Add("%");
ddlMFT.Items.Add("Value");
ddlMFT.CssClass = "form-control";
ddlMFT.Width = Unit.Percentage(100);
ddlMFT.ID = "ddlManFeesType" + serCount;
ddlManFeesType.Add(ddlMFT);
c5.Controls.Add(ddlMFT);
c5.Width = Unit.Percentage(5);
// Add Management Fees Value...
TextBox txtMFVal = new TextBox();
txtMFVal.CssClass = "form-control";
txtMFVal.Attributes.Add("placeholder", "0.000");
txtMFVal.Style.Add("text-align", "right");
txtMFVal.Width = Unit.Percentage(100);
// txtMFVal.ID = "txtManFeesValue" + serCount;
txtMFVal.AutoPostBack = true;
txtMFVal.TextChanged += new EventHandler(txtManFeesVal_TextChange);
txtManFeesValue.Add(txtMFVal);
c6.Controls.Add(txtMFVal);
c6.Width = Unit.Percentage(10);
// Add Manpower Value...
TextBox txtManp = new TextBox();
txtManp.ID = "txtManpower" + serCount;
txtManp.CssClass = "form-control";
txtManp.Attributes.Add("placeholder", "0");
txtManp.Style.Add("text-align", "center");
txtManPower.Add(txtManp);
c3.Controls.Add(txtManp);
c3.Width = Unit.Percentage(10);
s.manPower = 0;
// Add Quoted Value...
TextBox txtQuotVal = new TextBox();
txtQuotVal.ID = "txtQuotedValue" + serCount;
txtQuotVal.CssClass += "form-control";
// txtQuotVal.Text = "0.000";
txtQuotVal.Attributes.Add("placeholder", "0.000");
txtQuotVal.Style.Add("text-align", "right");
txtQuotVal.AutoPostBack = true;
txtQuotVal.ClientIDMode = ClientIDMode.Static;
txtQuotVal.TextChanged += (o, ep) => {
TextBox t = sender as TextBox;
if (t.Text == "")
{
t.Text = "0.000";
}
txtPrjValue.Text = (int.Parse(txtPrjValue.Text) + int.Parse(t.Text)).ToString();
};
txtQuotValue.Add(txtQuotVal);
c4.Controls.Add(txtQuotVal);
c4.Width = Unit.Percentage(10);
// Add Remarks Box...
TextBox txtRem = new TextBox();
txtRem.ID = "txtRemarks" + serCount;
txtRem.CssClass += "form-control";
txtRem.ClientIDMode = ClientIDMode.Static;
txtRem.Width = Unit.Percentage(100);
txtRemarks.Add(txtRem);
c7.Controls.Add(txtRem);
c7.Width = Unit.Percentage(35);
s.quotedValue = 0;
// Add the cells to the new row...
r.Cells.Add(c0);
r.Cells.Add(c1);
r.Cells.Add(c2);
r.Cells.Add(c5);
r.Cells.Add(c6);
r.Cells.Add(c3);
r.Cells.Add(c4);
r.Cells.Add(c7);
// Add the new row...
tblServices.Rows.Add(r);
serCount++;
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
Upon TextChanged of txtMFVal text, it does PostBack but it doesn't call the attached event handler, shown below:
protected void txtManFeesVal_TextChange(object sender, EventArgs e)
{
TextBox txtMFV = sender as TextBox;
// Get the parent cell of the TextBox...
TableRow tr = txtMFV.Parent.Parent as TableRow;
TextBox txtSCV = tr.Cells[2].Controls[0] as TextBox;
TextBox txtMFT = tr.Cells[5].Controls[0] as TextBox;
double scv = Double.Parse(txtSCV.Text);
double mfv = Double.Parse(txtMFV.Text);
double v = 0;
if (txtMFT.Text == "%")
{
v = (scv * mfv) / 100;
}
else
{
v = scv + mfv;
}
TextBox txtQP = tr.Cells[6].Controls[0] as TextBox;
txtQP.Text = v.ToString();
// Postback to refresh contents from Server Side...
string scriptRefresh = "document.getElementById('" + btnASPClickMe.ClientID + "').click();";
Page.ClientScript.RegisterStartupScript(typeof(Page), "refreshscript", scriptRefresh, true);
}
I have tried so many tricks I have found on the net and all didn't work.
Please, help.
Thanks,
I want to add some panel dynamically into a single panel on a button click. And each dynamic panel consist of multiple text box in horizontally. And then I want to save those text box value into the database.
I have completed to add dynamic panel and horizontal multiple text box into that panel. But couldn't know how to save them into database.
Here is the code I have written:
int v = 0;
TextBox txt1;
TextBox txt2;
TextBox txt3;
TextBox txt4;
TextBox txt5;
ComboBox cmb4;
public void tett()
{
v = 0;
Panel whitePanel = new Panel();
whitePanel.Name = "wt";
// Quantity
txt1 = new TextBox();
txt1.Location = new Point(192, 38);
txt1.Size = new Size(120, 24);
txt1.Name = "text" + v ;
txt1.Text = txt1.Name;
v = v + 1;
// Total Price
txt2 = new TextBox();
txt2.Location = new Point(566, 38);
txt2.Size = new Size(120, 24);
txt2.Name = "text" + v;
txt2.Text = txt2.Name;
txt2.TextChanged += Txt2_TextChanged;
v = v + 1;
// Unit Price
txt3 = new TextBox();
txt3.Location = new Point(753, 38);
txt3.Size = new Size(120, 24);
txt3.Name = "text" + v;
txt3.Text = txt3.Name;
v = v + 1;
// Sell Price
txt4 = new TextBox();
txt4.Location = new Point(903, 38);
txt4.Size = new Size(120, 24);
txt4.Name = "text" + v;
txt4.Text = txt4.Name;
v = v + 1;
// Product
txt5 = new TextBox();
txt5.Location = new Point(5, 38);
txt5.Size = new Size(120, 24);
txt5.Name = "text" + v;
txt5.Text = txt5.Name;
txt5.AutoCompleteSource = AutoCompleteSource.CustomSource;
txt5.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt5.MouseClick += textBox5_MouseClick;
Label lbl3 = new Label();
Label lbl4 = new Label();
Label lbl5 = new Label();
Label lbl6 = new Label();
Label lbl7 = new Label();
Label lbl8 = new Label();
lbl3.Location = new Point(5, 15);
lbl3.Text = "Product";
lbl4.Location = new Point(192, 15);
lbl4.Text = "Quantity";
lbl5.Location = new Point(379, 15);
lbl5.Text = "Unit";
lbl6.Location = new Point(566, 15);
lbl6.Text = "Total Price";
lbl7.Location = new Point(753, 15);
lbl7.Text = "Unit Purchase Price";
lbl8.Location = new Point(903, 15);
lbl8.Text = "Unit Sell Price";
cmb4 = new ComboBox();
// Unit
cmb4.Location = new Point(379, 38);
cmb4.Size = new Size(120, 24);
whitePanel.BackColor = ColorTranslator.FromHtml("#ECF0F5");
whitePanel.Location = new Point(1, a * 10);
whitePanel.Size = new Size(1330, 60);
var _button = new Button();
_button.Text = "Dispose";
_button.Name = "DisposeButton";
_button.Location = new Point(1053, 38);
_button.MouseClick += _button_MouseClick;
whitePanel.Controls.Add(_button);
a = a + 5;
v = v + 1;
whitePanel.Controls.Add(lbl3);
whitePanel.Controls.Add(lbl4);
whitePanel.Controls.Add(lbl5);
whitePanel.Controls.Add(lbl6);
whitePanel.Controls.Add(lbl7);
whitePanel.Controls.Add(lbl8);
whitePanel.Controls.Add(txt1);
whitePanel.Controls.Add(txt2);
whitePanel.Controls.Add(txt3);
whitePanel.Controls.Add(txt4);
whitePanel.Controls.Add(txt5);
whitePanel.Controls.Add(cmb4);
panel1.Controls.Add(whitePanel);
}
In this way the output is like this..... By click on the New Purchase this multiple panel with text box will appear:
Multiple dynamic panel with multiple text box
Here the way of setting text box name is not seems better way to me. I want to use an array for set the name of text boxes.
And after all I want to save those values into db by click on the save button using an array or for loop... But I don't know how to define it..
Can anyone please help me?
And thanks in advance
With this approach, a gridview is usefull.
But within your question, the approach is;
int rowNum = 1;
public void tett() {
Control[] controlsToAdd = { new TextBox(), new TextBox(), new ComboBox(), new TextBox(), new TextBox(), new TextBox(), new Button() };
string[] labels = { "Product", "Quantity", "Unit", "Total Price", "Unit Purchase", "Unit Sell Price" };
Panel whitePanel = new Panel() {
Name = "wt",
Dock = DockStyle.Top,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
AutoSize = true,
Padding = new Padding(0, 5, 0, 5),
BackColor = ColorTranslator.FromHtml("#ECF0F5")
};
int controlX = 5, controlY = 15, controlDistance = 15;
for (int i = 0; i < controlsToAdd.Length; i++) {
if (labels.Length > i) {
var label = new Label() {
Text = labels[i],
Location = new Point(controlX, controlY)
};
whitePanel.Controls.Add(label);
}
var control = controlsToAdd[i];
control.Location = new Point(controlX, controlY + 23);
control.Size = new Size(120, 24);
if (control is Button) {
control.Name = "disposeButton" + i;
control.Text = "Dispose";
control.Click += _button_MouseClick;
} else {
if(i == 0) { //if it is the Product textbox
((TextBox)control).AutoCompleteSource = AutoCompleteSource.CustomSource;
((TextBox)control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//control.MouseClick += textBox5_MouseClick;
}
control.Name = "Text" + i;
control.Text = "Row" + rowNum + " Text" + i;
}
whitePanel.Controls.Add(control);
controlX += 120 + controlDistance;
}
panel1.Controls.Add(whitePanel);
whitePanel.BringToFront();
rowNum++;
}
private void _button_MouseClick(object sender, EventArgs e) {
//button does its job here
((Button)sender).Parent.Parent.Controls.Remove(((Button)sender).Parent);
}
public SqlConnection Conn { get; }
void save() {
foreach(Panel whitePanel in panel1.Controls) {
var sqlString = "INSERT INTO products(productField, quantityField, unitField, priceField, purchaseField, sellPriceField) VALUES (";
foreach (Control control in whitePanel.Controls) {
if(!(control is Label) && !(control is Button)) { //So, textbox or combobox remained
sqlString += "'"+ control.Text +"', ";
}
}
sqlString = sqlString.Substring(0, sqlString.Length - 2) + ")";
//Assume you have previous construction of SqlConnection as name "Conn"
if (Conn != null) {
if (Conn.State != ConnectionState.Open) Conn.Open();
using (var cmd = new SqlCommand(sqlString, Conn)) {
cmd.ExecuteNonQuery();
}
Conn.Close();
}
Console.WriteLine(sqlString);
}
}
I have tested and works as expected. If it is not suit your needs, make me know.
I'm calling a function from another class to a form to load datagridView. when i add only one dataGirdViewButtonColumn its works but when i add two the second one is not added.Another problem i have found is the button is added to empty row..
Function
public void LoadDataGridrcv(DataTable d, DataGridView dg)
{
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
DataGridViewButtonColumn btn1 = new DataGridViewButtonColumn();
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate()
{
dg.Rows.Clear();
dg.ColumnCount = 7;
dg.Columns[0].Name = "Order No.";
dg.Columns[0].Width = 110;
dg.Columns[1].Name = "Order Date";
dg.Columns[1].Width = 100;
dg.Columns[2].Name = "Excepted rcv date";
dg.Columns[2].Width = 100;
dg.Columns[3].Name = "Supplier";
dg.Columns[3].Width = 150;
dg.Columns[4].Name = "Total Items";
dg.Columns[4].Width = 80;
dg.Columns[5].Name = "Total";
dg.Columns[5].Width = 80;
dg.Columns[6].Name = "Status";
dg.Columns[6].Width = 100;
dg.Columns.Add(btn);
btn.HeaderText = "Click to view";
btn.Text = "View";
btn.Name = "btn";
btn.UseColumnTextForButtonValue = true;
btn1.HeaderText = "Click to recieve";
btn1.Text = "Recieve";
btn1.Name = "btn1";
btn1.UseColumnTextForButtonValue = true;
});
foreach (DataRow row in d.Rows)
{
if (dg.InvokeRequired)
{
dg.BeginInvoke((MethodInvoker)delegate() { dg.Rows.Add(row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString(), row[5].ToString(), row[6].ToString()); });
}
Thread.Sleep(100);
}
}
}
Usage
reatail r = new reatail();
t = new Thread(() => r.LoadDataGridrcv(r.loadAllOrder(), dataGridView1));
t.Start();
I have to update my txtid , txtName ,txtAge ,txtContact..OnSelectionChange of ListPicker , but even after selecting items it is not updating txtfields . How can i step up on it ?
public partial class Update : PhoneApplicationPage
{
Button btnUpdate1 = null;
TextBox txtid = null;
TextBox txtName = null;
TextBox txtAge = null;
TextBox txtContact = null;
ListPicker lp = null;
int selectedItem ;
public Update()
{
InitializeComponent();
int x = noofrows();
createUpdateButton();
createListPicker();
selectedItem = Convert.ToInt32(lp.SelectedItem);
createTxtId(selectedItem);
createTxtName(selectedItem);
createTxtAge(selectedItem);
createTxtContact(selectedItem);
}
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
};
LayoutRoot.Children.Add(lp);
}
public void createUpdateButton()
{
btnUpdate1 = new Button();
btnUpdate1.Margin = new Thickness(100, 600, 0, 0);
btnUpdate1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
btnUpdate1.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
btnUpdate1.Height = 100;
btnUpdate1.Width = 150;
btnUpdate1.Content = "update";
btnUpdate1.Foreground = new SolidColorBrush(Colors.White);
btnUpdate1.Background = new SolidColorBrush(Colors.Black);
btnUpdate1.BorderBrush = new SolidColorBrush(Colors.White);
btnUpdate1.BorderThickness = new Thickness(3);
btnUpdate1.FontSize = 28;
LayoutRoot.Children.Add(btnUpdate1);
btnUpdate1.Click += (s, e) =>
{
UpdateDatabase(selectedItem);
};
}
public void createTxtId(int z)
{
int id = z ;
txtid = new TextBox();
txtid.Margin = new Thickness(12, 100, 0, 0);
txtid.Width = 400;
txtid.Height = 100;
txtid.FontSize = 28;
txtid.Foreground = new SolidColorBrush(Colors.Black);
txtid.BorderBrush = new SolidColorBrush(Colors.Black);
txtid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtid.BorderThickness = new Thickness(3);
txtid.IsReadOnly = true;
txtid.Text = " " + id;
LayoutRoot.Children.Add(txtid);
}
public void createTxtName(int z)
{
txtName = new TextBox();
txtName.Margin = new Thickness(12, 200, 0, 0);
txtName.Width = 400;
txtName.Height = 100;
txtName.FontSize = 28;
txtName.Foreground = new SolidColorBrush(Colors.Black);
txtName.BorderBrush = new SolidColorBrush(Colors.Black);
txtName.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtName.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtName.BorderThickness = new Thickness(3);
txtName.Text = SelectName(z);
txtName.Tap += (s, e) =>
{
if (txtName.Text == "Name")
{
txtName.Text = "";
}
};
txtName.LostFocus += (s, e) =>
{
if (txtName.Text == "")
{
txtName.Text = "Name";
}
};
LayoutRoot.Children.Add(txtName);
}
public void createTxtAge(int z)
{
txtAge = new TextBox();
txtAge.Margin = new Thickness(12, 300, 0, 0);
txtAge.Width = 400;
txtAge.Height = 100;
txtAge.FontSize = 28;
txtAge.Foreground = new SolidColorBrush(Colors.Black);
txtAge.BorderBrush = new SolidColorBrush(Colors.Black);
txtAge.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtAge.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtAge.BorderThickness = new Thickness(3);
txtAge.MaxLength = 2;
txtAge.Text = SelectAge(z);
txtAge.InputScope = new InputScope();
txtAge.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtAge.Tap += (s, e) =>
{
if (txtAge.Text == "Age")
{
txtAge.Text = "";
}
};
txtAge.LostFocus += (s, e) =>
{
if (txtAge.Text == "")
{
txtAge.Text = "Age";
}
};
LayoutRoot.Children.Add(txtAge);
}
public void createTxtContact(int z)
{
txtContact = new TextBox();
txtContact.Margin = new Thickness(12, 400, 0, 0);
txtContact.Width = 400;
txtContact.Height = 100;
txtContact.FontSize = 28;
txtContact.MaxLength = 10;
txtContact.Foreground = new SolidColorBrush(Colors.Black);
txtContact.BorderBrush = new SolidColorBrush(Colors.Black);
txtContact.VerticalAlignment = System.Windows.VerticalAlignment.Top;
txtContact.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
txtContact.BorderThickness = new Thickness(3);
txtContact.Text = SelectContact(z);
txtContact.InputScope = new InputScope();
txtContact.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.Number });
txtContact.Tap += (s, e) =>
{
if (txtContact.Text == "Contact")
{
txtContact.Text = "";
}
};
txtContact.LostFocus += (s, e) =>
{
if (txtContact.Text == "")
{
txtContact.Text = "Contact";
}
};
LayoutRoot.Children.Add(txtContact);
}
public Int32 noofrows()
{
int b = Convert.ToInt32((Application.Current as App).db.SelectList("select count(*) from details"));
return b;
}
public string returnID(int z)
{
return Convert.ToString((Application.Current as App).db.SelectList("select id from details where id =" + z));
}
public String SelectName(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select name from details where id =" + x));
}
public String SelectAge(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select age from details where id =" + x));
}
public String SelectContact(int x)
{
return Convert.ToString((Application.Current as App).db.SelectList("select contact from details where id =" + x));
}
public void UpdateDatabase(int ID)
{
if (txtName.Text=="Name")
{
MessageBox.Show("Enter a valid Name");
}
else if (txtAge.Text.Length>=3||txtAge.Text=="Age")
{
MessageBox.Show("Enter A valid Age (1-99)");
}
else if (txtContact.Text.Length != 10)
{
MessageBox.Show("Enter a valid Mobile number Of 10 digit");
}
else
{
string s1 = "update details set id='" + Convert.ToInt64(txtid.Text) + "', name = '" + txtName.Text + "', age = '" + txtAge.Text + "', contact = '" + txtContact.Text + "'where id = " + ID;
string s2 = Convert.ToString((Application.Current as App).db.SelectList(s1));
MessageBox.Show("Updated Successfully");
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
}
You are using so much code. Its would be better if you follow the MVM architecture and try to set Bind the textblocks to your viewModel. Lets consider the following scenario.
You have binded the xaml elements to selectedItem in your viewModel. Now when selectedItem's value is changed Notify event is triggered which will notify the UI and the values will automatically be updated.
I recommend you to study viewmodel and try to implement it. Its really easy and would save you a lot of hassle.
Try implementing some samples
Hope it helps :)
I got this ...
Actually if we want to update that we need to change text of each text box . So after the selection change , Try it like this.
public void createListPicker()
{
lp = new ListPicker();
lp.BorderBrush = new SolidColorBrush(Colors.White);
lp.BorderThickness = new Thickness(3);
lp.Margin = new Thickness(12, 5, 0, 0);
lp.Width = 400;
int x = noofrows();
for (int a = 1; a <= x; a++)
{
string str1 = returnID(a);
lp.Items.Add(str1);
}
lp.SelectionChanged += (s, e) =>
{
selectedItem = Convert.ToInt32(lp.SelectedItem);
txtid.Text = selectedItem.ToString();
txtName.Text = SelectName(selectedItem);
txtAge.Text = SelectAge(selectedItem);
txtContact.Text = SelectContact(selectedItem);
};
LayoutRoot.Children.Add(lp);
}
This will update Immediately after Every selection change Event .
After some minor difficulties with my basic test rating control not working because of the missing inline CSS stylesheet, I am trying to dynamically add a bunch of rating controls in a updatepanel when I click on a button in a different updatepanel. (These panels are both in a parent updatepanel, I have defined the triggers and set the updatemode to conditional). Anyways, when I click the button, he updates the updatepanel with the rating controls, but when I hover over them, he always displays 0 (the current rating), and does not change the rating control star image (filledStarRating). The code relevant to my problem (two methods):
protected void imbformulier_Click(Object sender, ImageClickEventArgs e)
{
imbFormulier.Visible = false;
imbGebruikers.Visible = false;
imbModellen.Visible = false;
pnlGegevens1.Visible = false;
pnlGegevens2.Visible = true;
pnlNavigatie.Visible = true;
pnlEval.Visible = true;
//kijken welk formulier moet ingevuld worden adhv de ddl's en dit meegeven aan de zelfgemaakte klasse
List<EvaluatieFormulier> mijnformulieren = (List<EvaluatieFormulier>)Session["mijnformulieren"];
IEnumerator<EvaluatieFormulier> enumerator = mijnformulieren.GetEnumerator();
EvaluatieFormulier meetegeven = new EvaluatieFormulier();
while (enumerator.MoveNext())
{
if (((enumerator.Current.GebruikergeevalueerdID == ddlGebruikers.SelectedValue) && (enumerator.Current.ModelID == Convert.ToInt32(ddlModellen.SelectedValue))))
{
meetegeven = enumerator.Current;
//Eventueel tekst veranderen als er al was gewerkt aan een bepaalde evaluatie
if (meetegeven.Tijdaangewerkt == 0)
{
lblInfo.Text = "Evaluatie gestart van " + ddlGebruikers.SelectedItem.Text;
lblDatum.Text = "Evaluatie begonnen op: "+ DateTime.Now.Date.ToString("d/M/yyyy") + "(Vandaag)" ;
//updaten in database
Session["aantalminutenaangewerkt"] = 0;
Session["aantalsecondenaangewerkt"] = 0;
timTijdAanGewerkt.Enabled = true;
lblTijd.Visible = true;
}
else
{
lblInfo.Text = "Evaluatie verdergezet van " + ddlGebruikers.SelectedItem.Text;
lblDatum.Text = "Evaluatie laatst gewijzigd : " + meetegeven.Tijdingevuld.ToString();
Session["aantalminutenaangewerkt"] = meetegeven.Tijdaangewerkt;
Session["aantalsecondenaangewerkt"] = 0;
timTijdAanGewerkt.Enabled = true;
lblTijd.Visible = true;
}
}
}
//Rating controls aanmaken voor elke criteria
List<AjaxControlToolkit.Rating> lijstratingcontrols = new List<AjaxControlToolkit.Rating>();
Model modelmetdomeinen = new Model() ;
IEnumerator<Model> modelenum = Database.laadModellenIn().GetEnumerator();
while (modelenum.MoveNext())
{
if (modelenum.Current.ModelID == meetegeven.ModelID)
modelmetdomeinen = modelenum.Current;
}
//foreach (Domein domein in modelmetdomeinen.Domeins)
//{
// foreach (Criterium criterium in domein.Criteriums)
// {
// AjaxControlToolkit.Rating ratingcontrol = new AjaxControlToolkit.Rating();
// ratingcontrol.ID = criterium.CriteriumNaam;
// ratingcontrol.StarCssClass = "ratingStar";
// ratingcontrol.EmptyStarCssClass = "emptyStarRating";
// ratingcontrol.WaitingStarCssClass = "emptyStarRating";
// ratingcontrol.FilledStarCssClass = "filledStarRating";
// ratingcontrol.Changed += new AjaxControlToolkit.RatingEventHandler(rating_Changed);
// ToolkitScriptManager1.RegisterAsyncPostBackControl(ratingcontrol);
// lijstratingcontrols.Add(ratingcontrol);
// }
//}
//Evaluatieform formulier = new Evaluatieform(meetegeven,lijstratingcontrols);
Table evaluatietabel = new Table();
int domeinteller =0;
foreach (Domein domein in modelmetdomeinen.Domeins)
{
domeinteller++;
if (domeinteller < 4)
{
TableRow domeinrij = new TableRow();
TableCell domeintitel = new TableCell();
domeintitel.Text = domeinteller + ". " + domein.DomeinNaam;
domeintitel.BorderStyle = BorderStyle.None;
domeinrij.Cells.Add(domeintitel);
evaluatietabel.Rows.Add(domeinrij);
foreach (Criterium criterium in domein.Criteriums)
{
int criteriumteller = 1;
TableRow criteriumrij = new TableRow();
TableCell criteriumtitel = new TableCell();
TableCell opvulcell = new TableCell();
TableCell ratingcell = new TableCell();
criteriumtitel.BorderStyle = BorderStyle.None;
opvulcell.BorderStyle = BorderStyle.None;
ratingcell.BorderStyle = BorderStyle.None;
criteriumtitel.Text = criteriumteller + ". " + criterium.CriteriumNaam;
AjaxControlToolkit.Rating ratingcontrol = new AjaxControlToolkit.Rating();
ratingcontrol.ID = criterium.CriteriumNaam;
ratingcontrol.StarCssClass = "ratingStar";
ratingcontrol.EmptyStarCssClass = "emptyStarRating";
ratingcontrol.WaitingStarCssClass = "emptyStarRating";
ratingcontrol.FilledStarCssClass = "filledStarRating";
ratingcontrol.Changed += new AjaxControlToolkit.RatingEventHandler(rating_Changed);
ratingcell.Controls.Add(ratingcontrol);
ratingcell.Attributes.Add("runat", "server");
ratingcell.Attributes.Add("onclick", "return false");
criteriumrij.Cells.Add(opvulcell);
criteriumrij.Cells.Add(criteriumtitel);
criteriumrij.Cells.Add(ratingcell);
evaluatietabel.Rows.Add(criteriumrij);
criteriumteller++;
}
}
}
evaluatietabel.BorderStyle = BorderStyle.None;
pnlEval.ContentTemplateContainer.Controls.Add(evaluatietabel);
Session["formulieractief"] = true;
pnlEval.Update();
pnlGegevens1.Update();
pnlGegevens2.Update();
}
I'm also adding the link to an image that shows my problem, so that you can see it for yourself:
We had the same issue recently and the problem was that the latest version of the AjaxControltoolkit seems to require a ToolkitScriptManager instead of the normal ScriptManager.
So just try changing your
asp:ScriptManager tag to
asp:ToolKitScriptManager or
ajax:ToolKitScriptManager
or whatever your namespace is.