How to retrieve data from dynamically created textboxes and build strings - c#

So I have some code, that creates a row of 4 textboxes. The data from those 4 textboxes will be combined to make a SQL query and then executed. The button to add a row can be hit an infinite amount of times. I have my IDs generated so that on the first click textbox one is txtBox1Row1, then on the second click it is txtBox1Row2 etc, etc.
Now I need a way to retrieve the data from each row and build SQL queries from them. Just to reiterate, I only need the data from the 4 textboxes in each row per loop (I assume thats how this will need to be done).
So how do I go about doing this?
Thanks a lot, the help is always appreciated. I was planning on doing it like this:
foreach (Control c in pnlArea.Controls)
{
if (c.ID.Contains("ddlArea"))
{
area.Add(((DropDownList)c).SelectedValue);
}
if (c.ID.Contains("txtArea"))
{
areaOther.Add(((TextBox)c).Text);
}
if (c.ID.Contains("ddHazard"))
{
hazard.Add(((DropDownList)c).SelectedValue);
}
if (c.ID.Contains("txtHazard"))
{
hazardOther.Add(((TextBox)c).Text);
}
if (c.ID.Contains("txtHazardDesc"))
{
hazardDesc.Add(((TextBox)c).Text);
}
if (c.ID.Contains("txtActionDesc"))
{
actionDesc.Add(((TextBox)c).Text);
}
if (c.ID.Contains("calDueDate"))
{
dueDate.Add(((Calendar)c).SelectedDate);
}
}

Per Nkosi, you'd want to encapsulate your textbox 'area' in a form.
What I would recommend is looping through each textbox in the form and storing in a dictionary.
Here's what that might look like:
Dictionary<string, string> textBoxVals = new Dictionary<string, string>();
Control form = this.FindControl("form1") as Control;
TextBox tb;
foreach (Control c in form.Controls)
{
if (c.GetType() == typeof(TextBox))
{
tb = c as TextBox;
textBoxVals.Add(tb.ID, tb.Text);
}
}
Then you'd be able to loop through the dictionary to build your SQL string. The dictionary would contain both the dynamic name of the control and the value of the textbox.
Based on the code you posted it looks like maybe there are some other controls that might also be associated with each line. If that's the case, you can create another if statement in the foreach loop to handle different control types, so that you're saving the proper parameters of them.
I hope that helps.

Related

Is there a function to save the number of checked checkboxes in a variable?

I have a wpf app with 20 Checkboxes.
Is there a function to Safe the number of the checkboxes which are checked in a variable.
If there is an other possibility to use the number without saving it in a variable first, that would help me too.
Thanks!
There's nothing built-in, but a loop or Linq query shouldn't be too hard. If you want all checkboxes on the form, you could just do
int count = 0;
for (var control in parent.Children)
{
if (control is CheckBox && ((CheckBox)control).IsChecked)
{
count++;
}
}
or
int count = parent.Children.OfType<CheckBox>()
.Where(cb => cb.IsChecked)
.Count();
If you have move specific conditions (e.f. checkboxes that have a specific name pattern), then just add that to the if or Where clause.

Can I select checkboxes by ID?

I would like to select checkboxes
not by Design name but by parameters. More specifically, I would like to
check the checkboxes which has the parameters which are also in the data
retrieved from the database.
Example code :
(checkBox) C1.checked = true;
This is how I can set checked right now,
but I want to do something like...
string[] datas = db.getData();
foreach (string data in datas)
{
if (data.Equals("C1"))
{
C1.checked = true;
}
}
Of course I can do this for every checkboxes,
but there are over 50 checkboxes and I think it's stupid
to manually checking this but I couldn't find a way to select a particular checkbox based on the name.
Also, it would be really helpful if someone knows a way to group the textboxes,
so that I don't have to loop over every checkboxes every time. By that, I mean something like contains method within a group of checkboxes to find particular one.
It seems like your main goal is to find:
a way to group the textboxes, so that I don't have to loop over every
checkboxes every time.
You can create a Dictionary of string/Checkbox and select the checkbox that way.
Something like:
string key = "C1";
Dictionary<string, CheckBox> pairs = new Dictionary<string, CheckBox>();
pairs[key].Checked = true;
You Can do like below Using FindControl :
string[] datas = db.getData();
foreach (string data in datas)
{
CheckBox chk = this.Controls.Find(data, true).FirstOrDefault() as CheckBox;
if(chk !=null)
chk.Checked = true;
}

How to show a list in a datagrid cell?

I making a simple app for homework, and I have some data handling issues with it.
I have a DataGrid, and I uploaded it with data, but one of the rows shows "(collection)" because I uploaded that cells with a list. I would like to ask that how can I display the items of the list in the datagrid?
I created the datagrid with a List of a class, and the class has an other list.
If you only want to see the items in the list, then the following is a simple way to break your list into text:
void InputToDataGrid(IEnumerable<Records> records)
{
foreach (var record in records)
{
string listText = ""; //resets the text for each row in grid.
foreach (var item in listVariableToBreak)
{
listText += ", " +item.ToString();
}
dataGrid.Rows.Add(new[] {columnOne, columnTwo,..., listText});
}
}
Granted this is a very simple solution, written with some very low level code, that only is a solution for cases where you have a list--you will need to modify it to work with your current situation.

How to create session variables without knowing how many to create?

First of all, I'm using Visual Studio 2010 (Visual C#) and ASP.NET.
I'm working with a GridView that displays the current open positions at my company. I have a column of checkboxes where applicants can check off the position(s) for which they want to apply. To eliminate duplicate data, I created a linking table between my three main tables (POSITION, APPLICANT, and APPLICATION). It's made up of just the primary keys from each of those tables, so if one person applies for 3 positions, we won't have 3 whole applications to sift through.
I need to select the PositionID's of the positions they selected and store them in session variables for later use.
My question is, how do I do that without knowing how many they have checked? I don't want to just create a bunch of unnecessary variables that won't be used. I figure I'll have to use a foreach loop, but within the loop, I don't know how to tell it to create a new session variable and store the ID in it.
I sure hope this question makes sense. If you need clarification, let me know.
You can just create a List<int> or whatever datatype PositionID is and store that in the session variable.
In fact, I would create a property in the control or page as
public List<int> SelectedPositionIDList
{
get
{
if(Session["SelectedPositions"] != null)
return Session["SelectedPositions"] as List<int>;
return new List<int>();
}
set
{
Session["SelectedPositions"] = value;
}
}
you can iterate through the list of position ids as ,
foreach(int positionId in SelectedPositionIdList)
{
//Do something.
}
Of course, you need to grab the ids from the gridview when they want to save, or do some action. You can probably do that by looping through the gridview rows based on your implementation. Something like below.
List<int> positions = new List<int>();
foreach(GridviewRow row in gdPositions)
{
CheckBox cb = row.FindControl("checkbox") as CheckBox;
if(cb != null && cb.Checked)
positions.Add(/*find position id from row here*/);
}
if(positions.Count > 0)
Session["SelectedPositionIdList"] = positions;

How do I obtain selected rows in a DataGridView from different pages

I have a windows forms DataGridView, where I have data and a checkbox for each row.
I will select check box for a particular row and all the selected rows will be populated in another page.
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
selectedEmp+= row.Cells["EmpId"].Value + ",";
}
}
}
This works good only for one page.
When I navigate to another page, and click the selected rows, the previous one goes off.
How do I resolve it.
Thanks
cmrhema
Note :Sorry for the confusion, When I meant it works good for a page, I meant paging.
I think I need to add more inputs,
There are 10 pages in the gridview.
I select the first record from each page of the gridview, one after another by clicking next page( Page next button).
But only the record that was selected the last is getting displayed and others and ignored off.
What could be the prblm
You can use a List or Dictionary or any other collection type globally, using Program.cs or using a static class. And store the selected rows into the list before you leave the page.
Rather than using a comma delimited string string for your list of ids you can instead use a List.
Your code will then become something like this:
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true s
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
if (!listOfIds.Contains((int)row.Cells["EmpId"].Value))
{
listOfIds.Add(((int)row.Cells["EmpId"].Value));
}
}
}
}
You will need methods to remove items from this list so adding event handlers for the checkbox selected event will probably work better.
The List object itself can simple live as a class level object of the form that containst your DataGridView.
This gets a little bit more complicated if you are managing your paging across forms, but the same principles of maintaining a list of selected ids applies.

Categories