New line in FlowLayoutPanel - c#

I am using following code to generate controls dynamically inside a FlowLayoutPanel (win forms - c#). I want to add line break after completion of inner foreach.
var fullText = textBox1.Text;
List<string> listPoints = fullText.Split('#').ToList();
foreach (var listPoint in listPoints)
{
if (listPoint.Contains('^'))
{
var listTextboxes = listPoint.Split('^');
int textBoxCount = listTextboxes.Count();
int index = 1;
foreach (var listTextbox in listTextboxes)
{
CheckBox ck = new CheckBox();
ck.Text = listTextbox;
ck.AutoSize = true;
ck.CheckStateChanged += new EventHandler(this.CheckBox_CheckedChanged);
flowLayoutPanel1.Controls.Add(ck);
if (index < textBoxCount)
{
TextBox tb = new TextBox();
tb.AutoSize = true;
tb.TextChanged += new EventHandler(this.TextBox_TextChanged);
flowLayoutPanel1.Controls.Add(tb);
}
index++;
}
// code for New line break
}
else
{
CheckBox ck = new CheckBox();
ck.Text = listPoint;
ck.AutoSize = true;
ck.CheckStateChanged += new EventHandler(this.CheckBox_CheckedChanged);
flowLayoutPanel1.Controls.Add(ck);
flowLayoutPanel1.
}

Use the SetFlowBreak method:
Control lastControl = null;
if (listPoint.Contains('^')) {
var listTextboxes = listPoint.Split('^');
int textBoxCount = listTextboxes.Count();
int index = 1;
foreach (var listTextbox in listTextboxes) {
CheckBox ck = new CheckBox();
ck.Text = listTextbox;
ck.AutoSize = true;
ck.CheckStateChanged += new EventHandler(this.CheckBox_CheckedChanged);
flowLayoutPanel1.Controls.Add(ck);
if (index < textBoxCount) {
TextBox tb = new TextBox();
tb.AutoSize = true;
tb.TextChanged += new EventHandler(this.TextBox_TextChanged);
flowLayoutPanel1.Controls.Add(tb);
lastControl = tb;
} else {
lastControl = ck;
}
index++;
}
if (lastControl != null) {
flowLayoutPanel1.SetFlowBreak(lastControl, true);
}

Related

Where is data updated in a DataGridView?

I am creating a tab page entirley programatically from a button press in the root page of a tabbed control. At present all the page initialisation takes place in the button click method. After all the instantiation, data capture from file and so on, I finally want to adjust the column widths in the data grid view, so that all the row data appears without having to have horizontal scroll bars. With the help of all your contributors I have managed to get it all working but the last step. Running at full speed it appears the DataGridView is accessed before the data load from the table is complete as it fails with an exception because the count derived from RegistersGrid.ColumnCount (local variable l) is zero. It all works fine if I step through the code. I am assuming that I need to put a Mutex of some form to wait for the transfer to complete, but I can't work out where that is taking place in order to reset the flag! If someone can point me in the right direction or if there is better more structured way to approach this I would deeply appreciate the help :-)
I have included all the code in the method just in case, I am afraid I date back a long way so if this looks like the awkward child of assembler,pascal and c with a little c# thrown in, my apologies....it's my age :-)
private void AddModuleButton_Click(object sender, EventArgs e)
{
string ModuleID = null;
string ModuleTypeFileNumber = null;
string ModuleType = null;
int TabID = 0;
openFileDialog1.Filter = "Text Files (.txt)|*.txt";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
string newline;
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split((char)9);
ModuleTypeFileNumber = values[1];
}
if ((newline = reader.ReadLine()) != null)
{
string[] values = newline.Split();
ModuleID = values[0];
ModuleType = values[1];
}
bool AbsorbLines = true;
while (AbsorbLines && ((newline = reader.ReadLine()) != null))
{
string[] values = newline.Split();
if (values[0] == "Readings") AbsorbLines = false;
}
string[] columnnames = { "Summary", "access", "register", "Module & Name", "Value", "unit", "type", "Res" };
string[] columntypes = { "System.Boolean", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.String", "System.String" };
int[] columnwidth = { 1,2,3,35,10,5,5,5 };
DataTable dt = new DataTable();
for(int i =0; i < columnnames.Length; i++)
{
DataColumn colString = new DataColumn(columnnames[i]);
colString.DataType = System.Type.GetType(columntypes[i]);
dt.Columns.Add(colString);
}
while (ImportTable("Controls", reader.ReadLine(), dt, "RO")) { } // Import the "readings" section
while (ImportTable("Status bits", reader.ReadLine(), dt, "RW")) { } // Import the "controls" section
reader.Close();
registerTables.Add(ModuleID, dt);
// create a new tab page
TabPage page = new TabPage(ModuleID);
InterbusRegisters.TabPages.Add(page);
//
// tabPage1
//
Button ResizeButton = new Button();
Button RemoveButton = new Button();
Label VersionLabel = new Label();
Label SerialNolabel = new Label();
TextBox VersionNoTB = new TextBox();
TextBox SerialNoTB = new TextBox();
DataGridView RegistersGrid = new DataGridView();
//
// Set the properties of the DataGrid.
//
RegistersGrid.AccessibleName = ModuleID + "Grid";
RegistersGrid.Location = new System.Drawing.Point(3,29);
RegistersGrid.Width = page.Width - 6;
RegistersGrid.Height = page.Height - 29;
RegistersGrid.Anchor = (AnchorStyles.Top | AnchorStyles.Left);
RegistersGrid.DataSource = dt;
RegistersGrid.Dock = (DockStyle)2;
//
// RemoveButtonRegistersGrid
//
RemoveButton.BackColor = System.Drawing.Color.Red;
RemoveButton.Location = new System.Drawing.Point(3, 4);
RemoveButton.Name = "RemoveButton";
RemoveButton.Size = new System.Drawing.Size(75, 25);
RemoveButton.TabIndex = 0;
RemoveButton.Text = "Remove";
RemoveButton.UseVisualStyleBackColor = false;
RemoveButton.Click += new System.EventHandler(this.RemoveButton_Click);
//
// ResizeButton
//
ResizeButton.BackColor = System.Drawing.Color.DarkOrange;
ResizeButton.Location = new System.Drawing.Point(81, 4);
ResizeButton.Name = "ResizeButton";
ResizeButton.Size = new System.Drawing.Size(75, 25);
ResizeButton.TabIndex = 6;
ResizeButton.Text = "Resize";
ResizeButton.UseVisualStyleBackColor = false;
ResizeButton.Click += new System.EventHandler(this.ResizeButton_Click);
//
// SerialNolabel
//
SerialNolabel.AutoSize = true;
SerialNolabel.Location = new System.Drawing.Point(159, 10);
SerialNolabel.Name = "SerialNolabel";
SerialNolabel.Size = new System.Drawing.Size(53, 13);
SerialNolabel.TabIndex = 4;
SerialNolabel.Text = "Serial No:";
//
// SerialNoTB
//
SerialNoTB.Location = new System.Drawing.Point(215, 7);
SerialNoTB.Name = "SerialNoTB";
SerialNoTB.Size = new System.Drawing.Size(100, 20);
SerialNoTB.TabIndex = 1;
//
// VersionLabel
//
VersionLabel.AutoSize = true;
VersionLabel.Location = new System.Drawing.Point(318, 10);
VersionLabel.Name = "VersionLabel";
VersionLabel.Size = new System.Drawing.Size(45, 13);
VersionLabel.TabIndex = 5;
VersionLabel.Text = "Version:";
//
// VersionTB
//
VersionNoTB.Location = new System.Drawing.Point(366, 7);
VersionNoTB.Name = "VersionTB";
VersionNoTB.Size = new System.Drawing.Size(100, 20);
VersionNoTB.TabIndex = 2;
page.Controls.Add(ResizeButton);
page.Controls.Add(RemoveButton);
page.Controls.Add(VersionLabel);
page.Controls.Add(VersionNoTB);
page.Controls.Add(SerialNolabel);
page.Controls.Add(SerialNoTB);
page.Controls.Add(RegistersGrid);
page.Location = new System.Drawing.Point(4, 22);
page.Size = new System.Drawing.Size(716, 554);
page.TabIndex = 1;
page.UseVisualStyleBackColor = true;
page.Update(); // the following code fails
int k = dt.Columns.Count;
int l = RegistersGrid.ColumnCount;
for (int j = 0; j <= RegistersGrid.ColumnCount - 1; j++)
RegistersGrid.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
RegistersGrid.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
//datagrid has calculated it's widths so we can store them
for (int i = 0; i <= RegistersGrid.ColumnCount - 1; i++)
{
int colw = RegistersGrid.Columns[i].Width; //store autosized widths
RegistersGrid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; //remove autosizing
RegistersGrid.Columns[i].Width = colw; //set width to calculated by autosize
}
}
}

WinForms - Dynamically create textbox based on ComboBox selection

I am trying to create a TextBox based on the selection on ComboBox dynamically based on the following steps:
First step (Select a source from ComboBox):
Second step (Textbox should appear based on ComboBox.SelectedValue):
Last step (A new ComboBox should appear below):
I have created a createTextBox function using the following code:
public void createTextBox(int numPassenger)
{
TextBox[] passengerBoxes = new TextBox[numPassenger];
for (int u = 0; u < passengerBoxes.Count(); u++)
{
passengerBoxes[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in passengerBoxes)
{
string name = "passenger" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(244, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
Is there a way that I can modify my current function to adapt to the mentioned steps? Additionally, how can I find the dynamically created TextBox?
You can try the following code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
createTextBox(sender as ComboBox);
}
private void createTextBox(ComboBox cmb)
{
TextBox passengerBoxes = new TextBox();
string name = cmb.Text;
if (Controls.Find(name, true).Length == 0)
{
passengerBoxes.Name = name;
passengerBoxes.Text = name;
int textBoxCount = GetTextBoxCount();
passengerBoxes.Location = new Point(244, 32 + (textBoxCount * 28));
passengerBoxes.Visible = true;
this.Controls.Add(passengerBoxes);
if (cmb.Items.Count != 1)//last item remaining then we should not create new combo box
{
ComboBox newCombo = new ComboBox
{
Location = new Point(cmb.Location.X, 32 + ((textBoxCount + 1) * 28))
};
foreach (string str in cmb.Items)
if (cmb.Text != str)
newCombo.Items.Add(str);
newCombo.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
this.Controls.Add(newCombo);
}
}
else
MessageBox.Show("Textbox Already for the selected source " + name);
}
private int GetTextBoxCount()
{
int i = 0;
foreach (Control ctl in this.Controls)
{
if (ctl is TextBox) i++;
}
return i;
}

How to find specific dynamic control and get value

I am making student attendance system. I am creating dynamic control and assigning values from database. Now I want to know how to find desired dynamic control and how I will get value from it.
I don't know how I can find desired control using a foreach loop.
This is my code for creating dynamic controls.
public void genControl(StudentAttendence sta)
{
StudentAttendenceBSLDAL stabd = new StudentAttendenceBSLDAL();
List<string[]> liName = stabd.takStudent(sta);
counts = Convert.ToInt16(stabd.takStudent(sta).Count);
for (int i=0; i< stabd.takStudent(sta).Count;i++)
{
for(int j = 0; j<liName[i].Count();j++)
{
Label lblStudentname = new Label();
Label lblStId = new Label();
lblStId.Name = "lblStId"+i.ToString()+j.ToString();
lblStudentname.Name = "liName"+i.ToString()+j.ToString();
lblStId.AutoSize = true;
lblStudentname.AutoSize = true;
if (j==0)
{
lblStId.Text = liName[i][j].ToString();
}
if(j==1)
{
lblStudentname.Text = liName[i][j].ToString();
}
lblStId.AutoSize = true;
lblStudentname.AutoSize = true;
if (i == 1)
{
lblStId.Location = new Point(41, 229);
lblStudentname.Location = new Point(153, 7);
}
else
{
lblStId.Location = new Point(3, 7 + 20);
lblStudentname.Location = new Point(153, 7 + 20);
}
this.Controls.Add(lblStId);
panel1.Controls.Add(lblStudentname);
}
CheckBox cba = new CheckBox();
cba.Name = "cba" + i.ToString() ;
cba.Text = "A";
cba.AutoSize = true;
CheckBox cbp = new CheckBox();
cbp.Name = i.ToString() ;
cbp.Text = "P";
cbp.AutoSize = true;
CheckBox cbl = new CheckBox();
cbl.Name = "cbl" + i.ToString() ;
cbl.Text = "L";
cbl.AutoSize = true;
if (i == 1)
{
cbp.Location = new Point(590, 3);
cba.Location = new Point(631, 3);
cbl.Location = new Point(670, 3);
}
else
{
cbp.Location = new Point(590, 3 + 23);
cba.Location = new Point(631, 3 + 23);
cbl.Location = new Point(670, 3 + 23);
}
panel1.Controls.Add(cbp);
panel1.Controls.Add(cba);
panel1.Controls.Add(cbl);
}
}
This is button control event in which I am trying to find control and get it value.
private void button2_Click(object sender, EventArgs e)
{
StudentAttendence sta = new StudentAttendence();
StudentAttendenceBSLDAL stabd = new StudentAttendenceBSLDAL();
// List<string[]> liName = stabd.takStudent(sta);
for (int i=0;i<counts;i++)
{
CheckBox cbP = panel1.Controls.OfType<CheckBox>().FirstOrDefault(b => b.Name.Equals("cbp"+i.ToString()));
// Label stid = panel1.Controls.Find("lblStId" + i.ToString(), false).First() as Label;
if(!cbP.IsChecked)
{
MessageBox.Show("control found");
}
}
}
You can save your control list into a SortedList.
You can use this sorted list for further processing

CheckBoxList In GridView Only Remember The First Option Ticked When New Row Added

I have a grid view with multiple columns which allow user to fill in the data and they are able to add a new row after finishing filling the data. Among the columns, there is a column with CheckBoxList which I allow user to multiple select the option on the CheckBoxList but every time add a new row, only the first option select by the user is remain while other selection is gone. How am I able to let the option selected by the user remain while I add a new row?
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.SelectedValue = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = checkBoxListLCourse.SelectedValue.ToString();
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}
You need to maintain state for selected checkbox. On the button click 'Add new row' first get the state of each rows in a DataTable and add a blank row then populate that DataTable.
You need to maintain checkbox's selected item's state also. You can get selected values in a CSV as :
string selectedItems = String.Join(",",
checkBoxListLCourse.Items.OfType<ListItem>().Where(r => r.Selected)
.Select(r => r.Value));
and you can restore as :
string[] items = selectedItems.Split(',');
for (int i = 0; i < checkBoxListLCourse.Items.Count; i++)
{
if (items.Contains(checkBoxListLCourse.Items[i].Value))
{
checkBoxListLCourse.Items[i].Selected = true;
}
}
My answer. This answer has some problem like the checkbox list will automatically scroll to the most top when we tick on anything in the checkbox list.
private void SetPreviousDataLecturer()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 0; i < dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
LecturerGridView.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
textBoxLName.Text = dataTableCurrent.Rows[i]["LecturerName"].ToString();
textBoxLID.Text = dataTableCurrent.Rows[i]["LecturerID"].ToString();
textBoxLAdd.Text = dataTableCurrent.Rows[i]["LecturerAddress"].ToString();
textBoxLPNumber.Text = dataTableCurrent.Rows[i]["LecturerPNumber"].ToString();
textBoxLEAdd.Text = dataTableCurrent.Rows[i]["LecturerEAddress"].ToString();
checkBoxListLCourse.Text = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
string lecturerCourse = dataTableCurrent.Rows[i]["LecturerCourse"].ToString();
if (!string.IsNullOrEmpty(lecturerCourse))
{
for (int j = 0; j < lecturerCourse.Split(',').Length; j++)
{
checkBoxListLCourse.Items.FindByValue(lecturerCourse.Split(',')[j].ToString()).Selected = true;
}
}
textBoxLPassword.Text = dataTableCurrent.Rows[i]["LecturerPassword"].ToString();
rowIndex++;
}
}
}
}
private void AddNewRowToLecturerGV()
{
int rowIndex = 0;
if (ViewState["LecturerGridView"] != null)
{
DataTable dataTableCurrent = (DataTable)ViewState["LecturerGridView"];
DataRow dataRowCurrent = null;
if (dataTableCurrent.Rows.Count > 0)
{
for (int i = 1; i <= dataTableCurrent.Rows.Count; i++)
{
TextBox textBoxLName = (TextBox)LecturerGridView.Rows[rowIndex].Cells[1].FindControl("LecturerName");
TextBox textBoxLID = (TextBox)LecturerGridView.Rows[rowIndex].Cells[2].FindControl("LecturerID");
TextBox textBoxLAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[3].FindControl("LecturerAddress");
TextBox textBoxLPNumber = (TextBox)LecturerGridView.Rows[rowIndex].Cells[4].FindControl("LecturerPNumber");
TextBox textBoxLEAdd = (TextBox)LecturerGridView.Rows[rowIndex].Cells[5].FindControl("LecturerEAddress");
CheckBoxList checkBoxListLCourse = (CheckBoxList)LecturerGridView.Rows[rowIndex].Cells[6].FindControl("LecturerCourse");
TextBox textBoxLPassword = (TextBox)LecturerGridView.Rows[rowIndex].Cells[7].FindControl("LecturerPassword");
dataRowCurrent = dataTableCurrent.NewRow();
dataRowCurrent["RowNumber"] = i + 1;
dataTableCurrent.Rows[i - 1]["LecturerName"] = textBoxLName.Text;
dataTableCurrent.Rows[i - 1]["LecturerID"] = textBoxLID.Text;
dataTableCurrent.Rows[i - 1]["LecturerAddress"] = textBoxLAdd.Text;
dataTableCurrent.Rows[i - 1]["LecturerPNumber"] = textBoxLPNumber.Text;
dataTableCurrent.Rows[i - 1]["LecturerEAddress"] = textBoxLEAdd.Text;
string lecturerCourse = string.Empty;
foreach (ListItem item in checkBoxListLCourse.Items)
{
if (item.Selected)
{
if (!string.IsNullOrEmpty(lecturerCourse))
{
lecturerCourse += ",";
}
lecturerCourse += item.Value;
}
}
dataTableCurrent.Rows[i - 1]["LecturerCourse"] = lecturerCourse;
dataTableCurrent.Rows[i - 1]["LecturerPassword"] = textBoxLPassword.Text;
rowIndex++;
}
dataTableCurrent.Rows.Add(dataRowCurrent);
ViewState["LecturerGridView"] = dataTableCurrent;
LecturerGridView.DataSource = dataTableCurrent;
LecturerGridView.DataBind();
}
}
else
{
Response.Write("ViewState is null.");
}
SetPreviousDataLecturer();
}

c# pass different variables to button onClick event

I would need different variables on button_Click event. For each button I need different billDetail and rowAmount values. Actually every button is giving the last values of the var Size.
I think is a easy problem but I'm doing this as hobby...please help me!
private void CashCounter_Load(object sender, EventArgs e)
{
var posXbutton = 120;
var posYbutton = 10;
var gapXbutton = 105;
var gapYbutton = 65;
var posXlabel = 5;
var posYlabel = 28;
var gapYlabel = 65;
using (var db = new GelatoProjectDBEntities())
{
#region working code
var items = (from x in db.ProductsLists
select new { x.Id, x.Product, x.Category, x.Size, x.Price, x.Market, x.Image }
).Where(x => x.Market == "Retail")
.ToArray();
var categories = (from x in items
select x.Category)
.Distinct();
foreach (var category in categories)
{
TabPage TabProduct = new TabPage(category);
TabProduct.BackColor = System.Drawing.Color.White;
tabControl1.TabPages.Add(TabProduct);
var products = (from i in items
where i.Category == category
select i.Product)
.Distinct()
.ToList();
foreach (var product in products)
{
string labelName = "label" + product;
var label = new Label();
label.AutoSize = false;
label.Location = new System.Drawing.Point(posXlabel, posYlabel);
label.Name = labelName;
label.Size = new System.Drawing.Size(110, 17);
label.TabIndex = 0;
label.Text = product;
label.RightToLeft = RightToLeft.Yes;
posYlabel = posYlabel + gapYlabel;
TabProduct.Controls.Add(label);
var sizes = (from i in items
where i.Product == product
//select i.Size)
select new { i.Id, i.Product, i.Category, i.Size, i.Price, i.Market, i.Image })
.Distinct()
.ToList();
foreach (var size in sizes)
{
BillDetail = size.Size+" "+product;
BillTotal = "£ "+size.Price;
RowAmount = size.Price;
string buttonName = "button" + product;
var button = new Button();
button.Location = new Point(posXbutton, posYbutton);
button.Name = buttonName;
button.Size = new Size(100, 50);
button.Text = size.Size;
button.BackColor = System.Drawing.Color.LightGray;
button.Click += new System.EventHandler(button_Click);
posXbutton = posXbutton + gapXbutton;
TabProduct.Controls.Add(button);
}
posXbutton = 120;
posYbutton = posYbutton + gapYbutton;
}
posXbutton = 120;
posYbutton = 10;
gapXbutton = 105;
gapYbutton = 65;
posXlabel = 5;
posYlabel = 28;
gapYlabel = 65;
}
}
#endregion
}
private void button_Click (object sender, EventArgs e)
{
ListViewItem NewBillProduct = new ListViewItem(BillDetail);
NewBillProduct.SubItems.Add("£");
NewBillProduct.SubItems.Add(RowAmount.ToString("F"));
listViewBillDetail.Items.Add(NewBillProduct);
BillTotalAmount = BillTotalAmount + double.Parse(RowAmount.ToString("F"));
ItemsTotal = ItemsTotal + 1;
textBoxTotal.Text = (BillTotalAmount.ToString("C", nfi)).ToString();
textBoxItems.Text = (ItemsTotal).ToString();
}
You can use Tag property of Button to store related Size object there:
button.Tag = size;
Then in click event handler you can retrieve this object:
private void button_Click (object sender, EventArgs e)
{
var button = (Button)sender;
var size = (Size)button.Tag;
// use size.Size or size.Price
// etc
}
Note: You can store several objects in Tag if you'll put them into array or list.

Categories