i'm new to c# programming, I had coded in c#(winforms) to get the output as: if an Item in the list box is clicked then the items should be displayed in the text box ,i had coded but its little bit hectic to implement to go further.
public partial class Form1 : Form
{
TextBox[] tb = new TextBox[5];
TextBox[] t = new TextBox[5];
TextBox[] t1 = new TextBox[5];
int[] tblist = new int[5];
public Form1()
{
InitializeComponent();
tb[0] = new TextBox();
tb[1] = new TextBox();
tb[2] = new TextBox();
tb[3] = new TextBox();
tb[4] = new TextBox();
t[0] = new TextBox();
t[1] = new TextBox();
t[2] = new TextBox();
t[3] = new TextBox();
t[4] = new TextBox();
t1[0] = new TextBox();
t1[1] = new TextBox();
t1[2] = new TextBox();
t1[3] = new TextBox();
t1[4] = new TextBox();
} //how can I simplify this by not assigning new to every textbox that i had created
// this button click is used to save items in the textbox in the listbox selected item
here how can we minimize the code : listbox selected index differs but the functions remains the same..
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
tb[0].Text = textBox1.Text;
tb[1].Text = textBox2.Text;
tb[2].Text = textBox3.Text;
tb[3].Text = textBox4.Text;
tb[4].Text = textBox5.Text;
}
if (listBox1.SelectedIndex == 1)
{
t[0].Text = textBox1.Text;
t[1].Text = textBox2.Text;
t[2].Text = textBox3.Text;
t[3].Text = textBox4.Text;
t[4].Text = textBox5.Text;
}
if (listBox1.SelectedIndex == 2)
{
t1[0].Text = textBox1.Text;
t1[1].Text = textBox2.Text;
t1[2].Text = textBox3.Text;
t1[3].Text = textBox4.Text;
t1[4].Text = textBox5.Text;
}
}
//here an item is clicked in the list box., so then items in the text box can be store in the listbox selected index
private void listBox1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == 0)
{
textBox1.Text = tb[0].Text;
textBox2.Text = tb[1].Text;
textBox3.Text = tb[2].Text;
textBox4.Text = tb[3].Text;
textBox5.Text = tb[4].Text;
}
if (listBox1.SelectedIndex == 1)
{ textBox1.Text = t[0].Text;
textBox2.Text = t[1].Text;
textBox3.Text = t[2].Text;
textBox4.Text = t[3].Text;
textBox5.Text = t[4].Text;
}
if (listBox1.SelectedIndex == 2)
{
textBox1.Text = t1[0].Text;
textBox2.Text = t1[1].Text;
textBox3.Text = t1[2].Text;
textBox4.Text = t1[3].Text;
textBox5.Text = t1[4].Text;
}
`
You may use a for loop for your arrays.
for(var i = 0; i < tb.Length; i++)
{
tb[i] = new TextBox();
t[i] = new TextBox();
t1[i] = new TextBox();
}
This is a snippet from code that I use.
Load your values into DataTables
and add a tableLayoutPanel to the form where you want the textboxes to go.
Call SetTextboxes function with datatable (or you can send your list here, just change the parameters and loop a little.
This will dynamically add textboxes to your form very quickly.
class SurroundingClass
{
private void SetTextboxes(datatable DT)
{
//Clear the previous textboxes
pnlLayoutExpenses.Controls.clear();
//loop through table and create new textboxes
foreach (DataRow row in DT.Rows)
formAddTextbox(row("dataTableColumnWhichHoldsTextboxText"));
}
private void formAddTextbox(string fieldname)
{
Integer elementCount = 0;
TextBox txtYourField = new TextBox();
txtYourField.Width = 100;
txtYourField.Height = 20;
//txtYourField.ReadOnly = true;
txtYourField.Text = fieldname;
txtYourField.tag = elementCount;
// Use tableLayoutPanel
pnlLayoutExpenses.SetCellPosition(txtType, new TableLayoutPanelCellPosition(0, elementCount));
pnlLayoutExpenses.Controls.Add(txtType);
}
}
Related
In my requirement I am creating dynamic controls by two events
Dropdownlist OnSelectedIndexChanged event
Onclick button event
In OnSelectedIndexChanged event i have created number of dynamic textbox.
Here I have create two dynamic textboxes.
I am getting all enquiry product list based on enquiry number from the dynamic textboxes on button click event
All are dynamic controls
While saving the productlist the checkbox control return null value
protected void ddlenqChaged(object sender, EventArgs e)
{
getenqTextbox();
}
protected void btnSearchClick(object sender, EventArgs e)
{
tblbill.Visible = true;
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicControls();
ViewState["Generated"] = "true";
}
}
protected void getenqTextbox()
{
enqPanel.Controls.Clear();
if (Convert.ToInt32(ddlNoofEnq.SelectedValue) > 0)
{
for (int i = 1; i <= Convert.ToInt32(ddlNoofEnq.SelectedValue); i++)
{
TextBox _txtCode = new TextBox();
_txtCode.ID = "txtEnqqNo" + i;
_txtCode.Attributes.Add("ClientIDMode", "Static");
_txtCode.Width = 75;
_txtCode.CssClass = "AtCompleteByEnq";
enqPanel.Controls.Add(_txtCode);
}
}
}
protected void CreateDynamicControls()
{
int m = 1;
//int encount = click.buttonclick;
if (Convert.ToInt32(ddlNoofEnq.SelectedValue) > 0)
{
Table tbldynamic = new Table();
for (int k = 1; k <= Convert.ToInt32(ddlNoofEnq.SelectedValue); k++)
{
Panel1.Controls.Clear();
TextBox tb = (TextBox)enqPanel.FindControl("txtEnqqNo" + k);
if (tb != null)
{
if (!String.IsNullOrEmpty(tb.Text))
{
List<Enquiry_ProductListBLL> objlst = Enquiry_ProductListBLL.GetEnquiry_ProductListBLLs(tb.Text);
foreach (Enquiry_ProductListBLL item in objlst)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableCell tc2 = new TableCell();
TableCell tc3 = new TableCell();
TableCell tc4 = new TableCell();
TableCell tc5 = new TableCell();
TableCell tc6 = new TableCell();
Master_ProductBLL objpdt = Master_ProductBLL.GetMaster_ProductBLL(item.ProductId);
CheckBox _chkRowNo = new CheckBox();
_chkRowNo.ID = "chkRowNo" + m;
_chkRowNo.Text = m.ToString();
_chkRowNo.Attributes.Add("ClientIDMode", "Static");
_chkRowNo.Attributes.Add("onclick", "getEnable(this);");
_chkRowNo.Checked = true;
TextBox _txtCode = new TextBox();
_txtCode.ID = "txtCodeRow" + m;
_txtCode.Attributes.Add("ClientIDMode", "Static");
_txtCode.Enabled = false;
_txtCode.Width = 75;
_txtCode.Attributes.Add("autocomplete", "off");
_txtCode.Text = objpdt.Code;
HiddenField _hdnPdtId = new HiddenField();
_hdnPdtId.ID = "hdnPdtId" + m;
_hdnPdtId.Value = item.ProductId.ToString();
HiddenField _hdEnqNo = new HiddenField();
_hdEnqNo.ID = "hdEnqNo" + m;
_hdEnqNo.Value = item.EnqNo;
_hdnPdtId.Value = item.ProductId.ToString();
TextBox _txtPdtName = new TextBox();
_txtPdtName.ID = "txtPdtNameRow" + m;
_txtPdtName.Attributes.Add("ClientIDMode", "Static");
_txtPdtName.Enabled = false;
_txtPdtName.Width = 150;
_txtPdtName.CssClass = "AtCompleteByName";
_txtPdtName.Text = objpdt.Name;
TextBox _txtQty = new TextBox();
_txtQty.ID = "txtQtyRow" + m;
_txtQty.Width = 80;
_txtQty.MaxLength = 8;
_txtQty.Attributes.Add("ClientIDMode", "Static");
//_txtQty.Attributes.Add("onblur", "GetTotal(this)");
//_txtQty.Enabled = false;
_txtQty.Text = item.Count.ToString();
DropDownList ddlUnits = new DropDownList();
ddlUnits.ID = "ddlUnits" + m;
ddlUnits.CssClass = "dropdowncss";
ddlUnits.Width = 100;
Bindings.BindUnitName(ddlUnits);
ddlUnits.Items.FindByText(item.PP).Selected = true;
tc.Controls.Add(_chkRowNo);
tc1.Controls.Add(_txtCode);
tc2.Controls.Add(_txtPdtName);
tc2.Controls.Add(_hdnPdtId);
tc2.Controls.Add(_hdEnqNo);
tc3.Controls.Add(_txtBrand);
tc4.Controls.Add(_txtThickness);
tc5.Controls.Add(ddlUnits);
tc6.Controls.Add(_txtQty);
tc.Attributes.Add("Width", "50px");
tr.Attributes.Add("id", "Rowid" + m);
tr.Attributes.Add("class", "paidRw");
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
tr.Cells.Add(tc3);
tr.Cells.Add(tc4);
tr.Cells.Add(tc5);
tr.Cells.Add(tc6);
tbldynamic.Rows.Add(tr);
m++;
}
}
}
}
Panel1.Controls.Add(tbldynamic);
}
}
Here I have override OnLoad event
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CreateDynamicControls();
getenqTextbox();
}
My problem is i cannot find controls from Panel1
CheckBox chk = (CheckBox)Panel1.FindControl(chkId);
if (chk != null)
{
if (chk.Checked == true)
{
//my process
}
}
FindControl returns null value.
Here I have create dynamic controls two times.
I cannot have any problem with enquiry textbox, it was created first, but the second time button click event controls are return null.
FindControl does not walk the hierarchy.
See doc Control.FindControl()
This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.
Since your CheckBox is not a first-level child of the Panel, it cannot be retrieved this way. If you need a generic solution, I suggest to implement a recursive FindControl.
I am facing troubles in creation of dynamic web controls. I have a SQL Databounded DropDownlist with DataTextField ="All_Columns" and DataValueField="DATA_TYPE".
Upon DropDownList1_SelectedIndexChanged i must check for the datatype as decimal or Varchar for the Selected value. If it is decimal i must call Createdynamicwebcontrols_decimal() and create DropDownList2. If it is varchar i must call Createdynamicwebcontrols_varchar().
Current Issue: Upon DropDownList2_SelectedIndexChanged i must create two dynamic textboxes and input values must be retained and search and display the data in a JQGrid with the help of Button Click event. But the DDL control hides completely
How to achieve above all features. Help needed please. New to dynamic web controls.
Aspx Code:
<asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="column_list_for_filter" DataTextField="All_Columns" DataValueField="DATA_TYPE" OnSelectedIndexChanged ="DropDownList5_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
<asp:SqlDataSource ID="column_list_for_filter" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" SelectCommand="SELECT COLUMN_NAME AS 'All_Columns', DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE')"></asp:SqlDataSource>
C# code:
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
//How to Proceed
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList5.SelectedValue == "decimal")
{
createdynamiccontrols_decimal();
}
else if(DropDownList5.SelectedValue == "int")
{
createdynamiccontrols_int();
}
else if(DropDownList5.SelectedValue == "varchar")
{
createdynamiccontrols_varchar();
}
//How to Proceed
}
protected void createdynamiccontrols_decimal()
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row;
row = new TableRow();
TableCell cell1;
cell1 = new TableCell();
//DropDownList2
DropDownList Range_DDL;
Range_DDL = new DropDownList();
Range_DDL.ID = "RandeDDL" + i.ToString();
Range_DDL.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL.Items.Insert(2, new ListItem("lesser than", "lesser than"));
Range_DDL.Items.Insert(2, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL.Items.Insert(2, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL.Items.Insert(2, new ListItem("Contains", "Contains"));
Range_DDL.Items.Insert(2, new ListItem("Is Null", "Is Null"));
Range_DDL.Items.Insert(2, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL.Items.Insert(2, new ListItem("Between", "Between"));
Range_DDL.AutoPostBack = true;
Range_DDL.SelectedIndexChanged += new System.EventHandler(Range_DDL_SelectedIndexChanged);
cell1.Controls.Add(Range_DDL);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
//DropdownList2 to create dynamic text boxes
protected void Range_DDL_SelectedIndexChanged(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
TableRow row;
row = new TableRow();
TableRow rowtwo;
rowtwo = new TableRow();
TableCell cell1;
cell1 = new TableCell();
TableCell cell2;
cell2 = new TableCell();
TableCell cell3;
cell3 = new TableCell();
TextBox tb1;
tb1 = new TextBox();
TextBox tb2;
tb2 = new TextBox();
Label lbl1;
lbl1 = new Label();
Label lbl2;
lbl2 = new Label();
//// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
Button addmore;
addmore = new Button();
addmore.ID = "Button" + j.ToString();
addmore.Text = "+";
addmore.Click += new System.EventHandler(addmore_click);
cell1.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
cell3.Controls.Add(addmore);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
rowtwo.Cells.Add(cell3);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
//Button Click to retrieve the input from dynamic generated text box and display in JQGrid.
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT a,b,c FROM TABLE WHERE " + DropDownList5.SelectedValue + " >= " + lowerboundd.Text + " AND " + DropDownList5.SelectedValue + " <= " + upperbound.Text, con);
**//Problems in retrieving the input of textboxes - Object Reference error**
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
You can find the source code and example on following link :
http://www.codeproject.com/Articles/20714/Dynamic-ASP-NET-control-creation-using-C
I also found this code online, I hope it would help you: You can modify this according to your needs in this code Button is added on the click of an another button.
Adding a new control to a form is really easy.
All you have to do is create a new instance of the control like any other class.
Eg:
Button NewButton = new button();
Then you fill out the properties of the control.
NewButton.Text = "My New Button";
After this setup an event handler.
NewButton.Click += new EventHandler(NewButton_Click);
Then in the button handler to tell which dynamic button was pressed you use the sender parameter.
void NewButton_Click(object sender, EventArgs e)
{
Button CurrentButton = (Button)sender;
CurrentButton.Text = "I was clicked";
}
Then finally the last step in setting the button up is to add the control to the form.
this.Controls.Add(NewButton);
I have a web page with multiple Drop Down list created at run time using Template fiels in GridView.
I have assigned event handler to DDL on selectedindexchange event.
But this event handler function is getting called only once and my gridview is getting updated only once.
How do I make my event handler function be called after every selection index change.
Here is MY Code
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("empName"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Insert(y, linkF);
y++;
}
else if (coloumn.ColumnName.Equals("empName"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Insert(y, bfield);
y++;
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa,String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "",conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
}
Mu Event Handler function dp_selected is called only Once. I have called my GridBind() function in Page_Load().
Any help would be highly appreciated.
Thanks in Advance
I have a form where I can add tabs into a tabcontrol by pressing a button on the form. There are 4 textboxes and then the name of the tab. I have added using system.io;
Where would I even start to create a save for all of the tabs? I have the save button created, I just don't know where to start. I would guess I would need a loop of some kind.
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public string status = "no";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add Labels
Label lb = new Label();
lb.Text = "Denomination:";
lb.Location = new System.Drawing.Point(150, 75);
lb.Name = "lbl";
lb.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb);
Label lb2 = new Label();
lb2.Text = "Year:";
lb2.Location = new System.Drawing.Point(150, 120);
lb2.Name = "lbl2";
lb2.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb2);
Label lb3 = new Label();
lb3.Text = "Grade:";
lb3.Location = new System.Drawing.Point(150, 165);
lb3.Name = "lbl3";
lb3.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb3);
Label lb4 = new Label();
lb4.Text = "Mint Mark:";
lb4.Location = new System.Drawing.Point(150, 210);
lb4.Name = "lbl4";
lb4.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb4);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "txt";
tb.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb);
TextBox tb1 = new TextBox();
tb1.Location = new System.Drawing.Point(250, 120);
tb1.Name = "txt1";
tb1.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb1);
TextBox tb2 = new TextBox();
tb2.Location = new System.Drawing.Point(250, 165);
tb2.Name = "txt2";
tb2.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb2);
TextBox tb3 = new TextBox();
tb3.Location = new System.Drawing.Point(250, 210);
tb3.Name = "txt3";
tb3.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb3);
//put data inside of textboxes
tb.Text = txtCoin.Text;
tb1.Text = txtYear.Text;
tb2.Text = txtGrade.Text;
tb3.Text = txtMint.Text;
// Add delete button
Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
bn.Click += MyClick;
myTabPage.Controls.Add(bn);
}
private void MyClick(object sender, EventArgs e)
{
Form2 myform = new Form2();
myform.ShowDialog();
if (status == "yes")
{ tabControl1.TabPages.Remove(tabControl1.SelectedTab); }
status = "no";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
int counter;
int ccounter;
string outLine;
string pathFileName = Path.Combine(Application.StartupPath, "coins.dat");
StreamWriter writeIt = new StreamWriter(pathFileName);
for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;)
{
}
writeIt.Close();
}
}
}
Use a foreach loop instead of your for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;) loop:
foreach (TabPage tabPage in tabControl.TabPages)
Your for loop is a infinite loop, do it like that:
for (counter = 0; counter < tabControl1.TabCount; counter++)
{
// Save the tab
}
I have the below code. I think I have pretty close to what I need. There is a main tab at startout (which does not contain tb, tb1, tb2, and tb3. Once I click the button, a tab is generated containing tb, tb1, tb2, tb3.
tb, tb1,tb2, and tb3 show errors of not existing. I simply cannot figure out how to get these saved.
public partial class Form1 : Form
{
public string status = "no";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add Labels
Label lb = new Label();
lb.Text = "Denomination:";
lb.Location = new System.Drawing.Point(150, 75);
lb.Name = "lbl";
lb.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb);
Label lb2 = new Label();
lb2.Text = "Year:";
lb2.Location = new System.Drawing.Point(150, 120);
lb2.Name = "lbl2";
lb2.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb2);
Label lb3 = new Label();
lb3.Text = "Grade:";
lb3.Location = new System.Drawing.Point(150, 165);
lb3.Name = "lbl3";
lb3.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb3);
Label lb4 = new Label();
lb4.Text = "Mint Mark:";
lb4.Location = new System.Drawing.Point(150, 210);
lb4.Name = "lbl4";
lb4.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb4);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "txt";
tb.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb);
TextBox tb1 = new TextBox();
tb1.Location = new System.Drawing.Point(250, 120);
tb1.Name = "txt1";
tb1.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb1);
TextBox tb2 = new TextBox();
tb2.Location = new System.Drawing.Point(250, 165);
tb2.Name = "txt2";
tb2.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb2);
TextBox tb3 = new TextBox();
tb3.Location = new System.Drawing.Point(250, 210);
tb3.Name = "txt3";
tb3.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb3);
//put data inside of textboxes
tb.Text = txtCoin.Text;
tb1.Text = txtYear.Text;
tb2.Text = txtGrade.Text;
tb3.Text = txtMint.Text;
// Add delete button
Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
bn.Click += MyClick;
myTabPage.Controls.Add(bn);
}
private void MyClick(object sender, EventArgs e)
{
Form2 myform = new Form2();
myform.ShowDialog();
if (status == "yes")
{ tabControl1.TabPages.Remove(tabControl1.SelectedTab); }
status = "no";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
int counter;
int ccounter;
string outLine ;
string pathFileName = Path.Combine(Application.StartupPath, "coins.dat");
StreamWriter writeIt = new StreamWriter(pathFileName);
foreach (TabPage tabPage in tabControl1.TabPages)
{
if (tabControl1.TabCount > 1)
{
outLine = tabPage + tb.Text + tb1.Text + tb2.Text + tb3.Text + "\t";
writeIt.WriteLine(outLine);
}
if (tabControl1.TabCount == 1)
{
outLine = tabPage + "\t";
writeIt.WriteLine(outLine);
}
}
writeIt.Close();
}
}
}
You need to store tb1, etc in fields in your form so they can be accessed by other methods.
tb, tb1,tb2, and tb3 show errors of not existing.
Yes, they would - you're declaring them as local variables within button1_Click. To access them from other methods, you'll either need to just examine the controls within the tab page, or declare them as instance variables instead. However, in that case you'd need to consider the fact that there may be multiple tab pages.
It sounds like you really just need to iterate over the controls within each tab page, and pick out the textboxes. Either that, or perhaps create your own subclass of TabPage which knows about the textboxes. Then you could find each instance of your custom TabPage and ask it to save itself.