Loop all textbox and collect values in c# asp.net - c#

I'm trying to get a list of strings from the database.
For each string in the list i want to add a label & textbox to the page.
On button submit I want to collect the textbox value as well as the corresponding label value then save it to the database.
I need help retrieving the values from the textboxes.
What I have so far:
Panel1 is on the aspx page
protected List<string> items = MyClass.GetItems();
protected void Page_Load(object sender, EventArgs e)
{
GenerateItemsTable();
}
private void GenerateItemsTable()
{
Table table = new Table();
table.ID = "Table1";
//PlaceHolder1.Controls.Add(table);
Panel1.Controls.Add(table);
foreach (var x in items)
{
TableRow row = new TableRow();
for (int y = 0; y < 1; y++)
{
TableCell labelCell = new TableCell();
labelCell.Controls.Add(CreateLabel(x));
labelCell.CssClass = "tdLabel";
row.Cells.Add(labelCell);
TableCell txbCell = new TableCell();
txbCell.Controls.Add(CreateRadNumericTextBox(x));
txbCell.Width = 30;
row.Cells.Add(txbCell);
TableCell dataTypeCell = new TableCell();
dataTypeCell.Text = "<span style='font-size: 10px; color: #777'>(student count)</span>";
dataTypeCell.Width = 100;
row.Cells.Add(dataTypeCell);
TableCell fourthCell = new TableCell();
if (x == items[items.Count - 1])
{
RadButton rb = new RadButton();
rb.ID = "submit";
rb.Text = "Submit Guidance";
rb.Skin = "Forest";
rb.Click += new EventHandler(submit_Click);
rb.AutoPostBack = true;
fourthCell.Controls.Add(rb);
row.Cells.Add(fourthCell);
}
else
{
row.Cells.Add(fourthCell);
}
}
table.Rows.Add(row);
}
}
private RadNumericTextBox CreateRadNumericTextBox(string x)
{
RadNumericTextBox rntb = new RadNumericTextBox();
rntb.ID = x;
rntb.Width = 40;
return rntb;
}
private Label CreateLabel(string x)
{
Label l = new Label();
l.ID = "label_" + x;
l.Text = "<label>" + x + "</label>";
return l;
}
protected void submit_Click(object sender, EventArgs e)
{
foreach (Control x in FindControl("Panel1").FindControl("Table1").Controls)
{
if (x is RadNumericTextBox)
{
//how to get the data??????/
}
}
}
(thanks to those that actually read the whole post)
-----------------updated solution--------------------------------------------
I decided to change it and store the list from the db at page_load. With the list stored i loop through the list and use FindControl() to access the textboxes. Something like this..
//a couple containers
protected class ItemVal
{
public int Value { get; set; }
public string Name { get; set; }
}
protected List<ItemVal> items = new List<ItemVal>();
//get the list from that database
protected void GetItems()
{
foreach (var x in MyClass.GetItems())
{
ItemVal i = new ItemVal();
i.Name = x;
items.Add(i);
}
}
//submit
protected void submit_Click(object sender, EventArgs e)
{
foreach (var x in items)
{
RadNumericTextBox rntb = FindControl(x.Name) as RadNumericTextBox;
x.Value = (int)rntb.Value;
}
}

You need to cast x to a RadNumericTextBox and then pull out the property values you want, like this:
RadNumericTextBox theRadNumericTextBox = x as RadNumericTextBox;
string val = theRadNumericTextBox.Text;
Then for the other controls you want, you will need to put if conditions for their types, like this:
if (x is Label)
{
Label theLabel = x as Label;
string valLabel = theLabel.Text;
}
Here is the full code for the method:
protected void submit_Click(object sender, EventArgs e)
{
foreach (Control x in FindControl("Panel1").FindControl("Table1").Controls)
{
Label theLabel;
RadNumericTextBox theRadNumericTextBox;
if (x is RadNumericTextBox)
{
RadNumericTextBox theRadNumericTextBox = x as RadNumericTextBox;
string val = theRadNumericTextBox.Text;
}
if (x is Label)
{
Label theLabel = x as Label;
string valLabel = theLabel.Text;
}
// Either store up in a list or save to the database on each loop; it is recommended to store a list and send all the changes at once for a database save, but that is your choice
}
}

Related

Injection of radiobuttonlist selected value into class

I want to create a webform with 4 types of phones like: LG, xiaomi, samsung and iphone. They will be in an Array and I will insert them into dynamic radiobuttonList in the page init.
Also, the user will have a textbox where he will put an amount of money he has. The user will also have a button that will calc if he have the budget for the selected phone from the list.
After the user selects the phone, write in the budget and press the button
he will get "in budget" or "not enough budget".
The class have property of the array to insert the all the array from the page init and will have 2 functions:
One function will take the budget number > will go to the 2nd function that will see the selected phone and the budget > do its calcs and return the result into the 1st func that will give the feedback.
Now where I am stuck:
if the class isnt made global - and i put it in init or in button click - it wont work, so im looking for a way to make it work but without putting it global
so far i managed to inject the selected value into a class property and than compare - but i want to know if there is a way that this can happen with array inside class property
maybe if anyone can help me out and refer me to a guide where i can learn more about this subject (how inject selected value into function of a class and etc) ill be glad! as everything i see is C# with console but i work with ASP.NET WEB APPLICATION (.netframework)
enter code here
namespace gfjsr{
public partial class WebForm1 : System.Web.UI.Page{
phone InsertUserInfo = new phone();
protected void Page_init(object sender, EventArgs e){
string[] myArr = new string[] { "samsung", "IPHONE", "XIAOMI","LG"};
RadioButtonList phoneList = new RadioButtonList();
phoneList.ID = "radioList";
for (int i = 0; i< myArr.Length; i++)
{
ListItem li = new ListItem();
li.Text = myArr[i];
li.Value = i.ToString();
phoneList.Items.Add(li);
}
Panel1.Controls.Add(phoneList);
Label budgetLb = new Label();
budgetLb.ID = "budglb";
budgetLb.Text = "write your budget";
Panel1.Controls.Add(budgetLb);
TextBox insertBudg = new TextBox();
insertBudg.ID = "budgTxt";
Panel1.Controls.Add(insertBudg);
Button myBtn = new Button();
myBtn.ID = "btn1";
myBtn.Click += new EventHandler(btn1_click);
myBtn.Text = "result";
Panel1.Controls.Add(myBtn);
Label Labelfeedback = new Label();
Labelfeedback.ID = "feedback";
Labelfeedback.Text = "";
Panel1.Controls.Add(Labelfeedback);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_click(object sender, EventArgs e)
{
InsertUserInfo.phoneChosen = ((RadioButtonList)FindControl("radioList")).SelectedItem.Text;
double UserBudget =
Convert.ToDouble(((TextBox)FindControl("budgTxt")).Text);
InsertUserInfo.BudgetYN(UserBudget);
((Label)FindControl("feedback")).Text = InsertUserInfo.feedback; }}}
namespace gfjsr{
public class phone{
private string _phoneChosen;
public string phoneChosen
{
get { return _phoneChosen; }
set { _phoneChosen = value; }
}
private string _feedback;
public string feedback
{
get { return _feedback; }
set { _feedback = value; }
}
public double Func1(string x)
{
double phonePrice = 0;
if( x == "samsung")
{
phonePrice = 4000;
}
if (x == "IPHONE")
{
phonePrice = 3500;
}
if (x == "XIAOMI")
{
phonePrice = 3000;
}
if (x == "LG")
{
phonePrice = 2000;
}
return phonePrice;
}
public void BudgetYN(double y)
{
if(y >= Func1(_phoneChosen))
{
_feedback = "positive";
}
else
{
_feedback = "no";
}
}
}
}

How to display value from not selected combobox c#

I need to display an unselected ComboBox value.
I have 10 ComboBoxes with tag values 1 through 10.
When I select a ComboBox with a tag value of 1, I have to check what is displayed from the ComboBox that has a tag value of 2.
Selecting a ComboBox with a tag value of 5 should give me the value of the ComboBox that has a tag value of 6.
public partial class workPlacePlan : Form
{
public workPlacePlan()
{
InitializeComponent();
}
private void workPlacePlan_Load(object sender, EventArgs e)
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
int cboId;
int i = 1;
string cboName; int c = 1;
var items = new Dictionary<int, string>();
ComboBox[] cbo = {
cbo_1, cbo_2
};
foreach(ComboBox cbos in cbo)
{
items.Add(0, "-------");
i = 1;
while (i <= 24)
{
cboId = i;
cboName = TimeSpan.FromHours(i).ToString("hh':'mm");
items.Add(cboId, cboName);
i++;
}
cbos.Tag = c;
cbos.DataSource = new BindingSource(items, null);
cbos.DisplayMember = "Value";
cbos.ValueMember = "Key";
items.Clear();
cbos.SelectedIndexChanged += new EventHandler(cboSelected);
c++;
}
}
public void cboSelected(object sender, EventArgs e)
{
ComboBox cb = ((ComboBox)sender);
int i_tmp;
int tg = Int32.Parse(cb.Tag.ToString());
if(tg % 2 == 0) //if is even
{
i_tmp= tg - 1;
}
else
{
i_tmp = tg + 1;
}
}
private void cmd_Save_Click(object sender, EventArgs e)
{
}
}
Solution:
public partial class workPlacePlan : Form
{
public workPlacePlan()
{
InitializeComponent();
}
private void workPlacePlan_Load(object sender, EventArgs e)
{
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
int cboId;
int i = 1;
string cboName; int c = 1;
var items = new Dictionary<int, string>();
ComboBox[] cbo = {
cbo_1_0, cbo_1_1, cbo_2_0, cbo_2_1, cbo_3_0, cbo_3_1, cbo_4_0, cbo_4_1, cbo_5_0, cbo_5_1, cbo_6_0, cbo_6_1,
cbo_13_0,cbo_13_1,cbo_14_0,cbo_14_1,cbo_15_0,cbo_15_1,cbo_16_0,cbo_16_1,cbo_17_0,cbo_17_1,cbo_18_0,cbo_18_1,
cbo_19_0,cbo_19_1
};
foreach(ComboBox cbos in cbo)
{
items.Add(0, "-------");
i = 1;
while (i <= 24)
{
cboId = i;
cboName = TimeSpan.FromHours(i).ToString("hh':'mm");
items.Add(cboId, cboName);
i++;
}
cbos.Tag = c;
cbos.DataSource = new BindingSource(items, null);
cbos.DisplayMember = "Value";
cbos.ValueMember = "Key";
cbos.SelectedIndex = 0;
items.Clear();
cbos.SelectedIndexChanged += new EventHandler(cboSelected);
c++;
}
}
public void cboSelected(object sender, EventArgs e)
{
ComboBox cb = ((ComboBox)sender);
int i_tmp;
int tg = Int32.Parse(cb.Tag.ToString());
int idx;
if(tg % 2 == 0) //if is even
{
i_tmp= tg - 1;
}
else
{
i_tmp = tg + 1;
}
//string y = cb.GetItemText(cb.SelectedItem);
//MessageBox.Show(y.ToString());
foreach (ComboBox cbt in panel1.Controls.OfType<ComboBox>()) {
if(Int32.Parse(cbt.Tag.ToString()) == Int32.Parse(i_tmp.ToString()))
{
idx = Int32.Parse(cbt.SelectedIndex.ToString());
cbt.SelectedIndex = idx;
MessageBox.Show(cbt.SelectedIndex.ToString());
}
}
}
private void cmd_Save_Click(object sender, EventArgs e)
{
}
}

Access Object created in another method C#

In this code I'm creating Few DataGridViews. Number of those depends on file which within each launch of application will be different, so is number of DataGridViews.
How can I Access particular dataGridView grid[i] and modify it from which event Form1_UserAddedRow was called in that method?
Code:
public void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"..\..\Base.txt");
int diet_num = 0;
int grid_num = 0;
foreach (string x in lines) diet_num++;
grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;
DataGridView[] grid = new DataGridView[grid_num];
for (int i = 0; i < grid_num; i++)
{
grid[i] = new DataGridView();
grid[i].Tag = i;
grid[i].Parent = this;
grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
grid[i].Visible = true;
grid[i].RowHeadersVisible = false;
grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
grid[i].UserAddedRow += Form1_UserAddedRow;
}
this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;
foreach (string x in lines)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.Width = Constant.DATAGRID_COLUMN_SIZE;
col.HeaderText = x;
int colIndex = grid[0].Columns.Add(col);
}
}
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
//I want to access grid[i] and modify it here.
}
You should be able to cast the Sender object parameter in your event handler to the type of DataGridView to retrieve the grid which has been effected.
You are getting the DataGridViewRowEventArgs e as the argument to your event handler and thus you can access the Row property like
e.Row.Cells["somename"].Value = "some_value";
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
var grid = sender as DataGridView;
if (grid == null) return;
//... do something
}

Adding a group of controls to a list

I am trying to add the values of 3 TextBox controls to a List, the problem is that these controls are added programmatically by the click of a button. I can't figure out how to get 3 TextBoxes grouped together so I can add their values to the List.
Here's some code:
Button click to add controls:
protected void Button_Add_Click(object sender, EventArgs e)
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
count = PlaceHolder_ForEntries.Controls.Count + 1;
ViewState["count"] = count;
createcontrols();
}
Method to add the controls
protected void createcontrols()
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
while (PlaceHolder_ForEntries.Controls.Count < count)
{
TextBox TextBox_Name = new TextBox();
TextBox TextBox_MemberNo = new TextBox();
TextBox TextBox_Points = new TextBox();
TextBox_Name.Attributes.Add("placeholder", "Navn");
TextBox_Name.ID = "TextBox_Name" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_Name.CssClass = "input-small";
TextBox_MemberNo.Attributes.Add("placeholder", "Medlemsnr.");
TextBox_MemberNo.ID = "TextBox_MemberNo" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_MemberNo.CssClass = "input-small";
TextBox_Points.Attributes.Add("placeholder", "Point");
TextBox_Points.ID = "TextBox_Points" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_Points.CssClass = "input-small";
PlaceHolder_ForEntries.Controls.Add(TextBox_Name);
PlaceHolder_ForEntries.Controls.Add(TextBox_MemberNo);
PlaceHolder_ForEntries.Controls.Add(TextBox_Points);
PlaceHolder_ForEntries.Controls.Add(new LiteralControl("<br />"));
}
}
Finally the code that runs on the save button click, to add the items to the list:
public struct content
{
public string name;
public string memberNo;
public int points;
}
List<content> rows = new List<content>();
protected void LinkButton_Submit_Attendees_Click(object sender, EventArgs e)
{
foreach (Control item in PlaceHolder_ForEntries.Controls)
{
if (item is TextBox)
{
string txt = item.ID.ToString(); // String to run RegEx on
string re1 = ".*?"; // Non-greedy match on filler
string re2 = "(\\d+)"; // Integer Number 1
Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(txt);
int id = Convert.ToInt32(m.Groups[1].ToString());
TextBox txtBox = (TextBox)item;
content row = new content();
if(item.ID.Contains(id.ToString()) && item.ID.Contains("Name"))
{
row.name = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("MemberNo"))
{
row.memberNo = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("Points"))
{
row.points = Convert.ToInt32(txtBox.Text);
}
rows.Add(row);
}
}
}
What I need is that for every third control this iterates over, the rows.Add(row) is called with row.name, row.memberNo and row.points all with their respective values.
You can use Linq's OfType find all your TextBoxes in the PlaceHolder:
var alltxt = PlaceHolder_ForEntries.Controls.OfType<TextBox>();
You can use Linq for all:
List<content> rows = PlaceHolder_ForEntries.Controls.OfType<TextBox>()
.Select(txt => new{
Txt = txt,
Number = new String(txt.ID.SkipWhile(c => !Char.IsDigit(c)).ToArray())
})
.GroupBy(x => x.Number)
.Select(g => new content{
name = g.First(x => x.Txt.ID.StartsWith("TextBox_Name")).Txt.Text,
memberNo = g.First(x => x.Txt.ID.StartsWith("TextBox_MemberNo")).Txt.Text,
points = int.Parse(g.First(x => x.Txt.ID.StartsWith("TextBox_Points")).Txt.Text)
})
.ToList();
I'm grouping by the numeric suffix that you have used for the ID (1-n).
I would change your LinkButton_Submit_Attendees_Click function:
protected void LinkButton_Submit_Attendees_Click(object sender, EventArgs e)
{
content row = new content();
foreach (Control item in PlaceHolder_ForEntries.Controls)
{
if (item is TextBox)
{
string txt = item.ID.ToString(); // String to run RegEx on
string re1 = ".*?"; // Non-greedy match on filler
string re2 = "(\\d+)"; // Integer Number 1
Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(txt);
int id = Convert.ToInt32(m.Groups[1].ToString());
TextBox txtBox = (TextBox)item;
if(item.ID.Contains(id.ToString()) && item.ID.Contains("Name"))
{
row.name = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("MemberNo"))
{
row.memberNo = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("Points"))
{
row.points = Convert.ToInt32(txtBox.Text);
}
if(!string.IsNullOrEmpty(row.name)
&& !string.IsNullOrEmpty(row.memberNo)
&& row.points > 0)){
rows.Add(row);
row = new content();
}
}
}
}

Selection of "DYNAMIC" dropdownlist items from a Table

//Code BehindFile
public void Button1_Click(object sender, EventArgs e)
{
while (reader.Read())
{
DropDownList ddl = new DropDownList();
string[] s = { "Present", "Absent1", "Absent2", "Absent3" };
for (int i = 0; i < 3; i++)
{
ddl.Items.Add(s[i]);
}
ddl.ID = "ddl";
TableCell c2 = new TableCell();
c2.Controls.Add(ddl);
r.Cells.Add(c2);
Table1.Rows.Add(r);
}
}
public void Button2_Click1(object sender, EventArgs e)
{
foreach (TableRow tr in Table1.Controls)
{
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[2] is DropDownList)
{
Response.Write(((DropDownList)tc.Controls[2]).SelectedItem.Text+" ");
}
}
Response.Write("<br/>");
}
Problem is with the Selection of dropdownlist items.I could not print the corresponding selected item values.could anyone help?
Check tc.Controls[2] when you are in the last nested foreach. Is it possible that your dropdown list is something other than the third control?
I don't see any reason that would force it to be the third control in that Cell.
You would probably be better off doing something like this:
if(tc.FindControl("ddl") != null)
{
Response.Write(((DropDownList)tc.FindControl("ddl")).SelectedItem.Text+" ");
}
instead of:
if (tc.Controls[2] is DropDownList)
{
Response.Write(((DropDownList)tc.Controls[0]).SelectedItem.Text+" ");
}

Categories

Resources