Can I select checkboxes by ID? - c#

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;
}

Related

How to retrieve data from dynamically created textboxes and build strings

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.

Store a value for an aspx checkbox?

I have a checkbox list filled by a list of ListItem, each ListItem having both text and a value like "8" or "5".
But I realized that a CheckBox does not have a value, its value is checked or not.
var listType = SettingsManager.Get("CRMCaseTypes");
var listStatus = SettingsManager.Get("CRMStatusReasons");
var listTypeItems = ParseSettingList(listType);
var listStatusItems = ParseSettingList(listStatus);
cblCRMType.DataSource = listTypeItems;
cblCRMType.DataBind();
cblCRMStatus.DataSource = listStatusItems;
cblCRMStatus.DataBind();
foreach (Control c in cblCRMStatus.Controls)
{
CheckBox cb = c as CheckBox;
if(cb != null && cb.(value........)
}
Is there some way I could store a value in each checkbox and use it again in code behind after the user clicks submit?
Thanks
Yes, you can. You can add a custom attribute to the CheckBox. You can use the HTML5 data attributes so your HTML will be HTML5 valid:
Set
foreach (Control c in cblCRMStatus.Controls)
{
CheckBox cb = c as CheckBox;
if(cb != null)
{
cb.Attributes.Add("data-MyField", myFieldVal);
}
}
Retrieve
foreach (Control c in cblCRMStatus.Controls)
{
CheckBox cb = c as CheckBox;
if(cb != null && cb.Attributes["data-MyField"].ToString())
{
// do something
}
}
How long do you want to re use it? If you want to store it temporarily, you can use session. If you want to store it longer, save it to a database or a file.
You could pull the value from the list that the checkboxes were bound to, referencing the relevant list item based on the index of the checkbox.
You could add it as an attribute -
SET:
myCheckBox.Attributes.Add("myKey","myValue");
GET:
var myKey = myCheckBox.Attributes["myKey"] != null ? myCheckBox.Attributes["myKey"].ToString() : "";
Is there some way I could store a value in each checkbox and use it again in code behind after the user clicks submit?
You can set it to a Session
Session["CbxList"] = YourCheckBoxList;
Then when you want to reference it just add the following:
if (Session["CbxList"] != null)
{
YourCheckBoxList = Session["CbxList"] as CheckBoxList;
}
and use.
I've included a link to sessions in case you or anyone else is not familiar with them:
http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx
You need to look at the Items collection, not the Controls collection:
foreach (ListItem item in cblCRMStatus.Items)
{
string value = item.Value;
}
Although probably no longer needed by OP I'll add my answer since this thread still ranks highly in Google. If this is an ASPxCheckBox you can make use of the JSProperties dictionary to store your value(s) like so:
cb.JSProperties["cpMyValue"] = "MyValue";
I would then usually use a callback from a ASPxGridView or CallbackPanel to get this back to server side (which is slightly out of scope of the original question).

Converting string to ToolStripMenuItem

I have a menu structure already set up on a form and I want to programatically enable or disable certain menu items using a database.
I have got to the last stage where I have a class of AllowedMenu and CodeNames (which match the toolstripmenuitems exactly), and all I want to do it convert the CodeName into a ToolStripMenuItem from a String.
How could I do this?
Seem to have found something that works...
var m = menuStrip1.Items.Find(menuItem.CodeName, true);
var o = m.ToList();
foreach (var p in o)
{
p.Visible = false;
}
Thanks all..
You can access ToolStripItems throught Items property of the ToolStrip. If you have exactly name of the item (in CodeName variable), you could do something like this:
if (toolStrip1.Items.ContainsKey(CodeName)) //Just in case...
{
var yourItem = toolStrip1.Items[CodeName];
}

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.

FindControl not working on GridView when inserting bound columns

I have a gridview with several ItemTemplates. The first contains a checkbox the rest contain textboxes.
I then added dynamically some bound controls like this:
BoundField bdfPrivName = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfPrivName, "PrivName", "Priv Name");
BoundField bdfDescription = new BoundField();
clsUtilities.SetBoundFieldLeft(ref bdfDescription, "PrivDesc", "Description");
BoundField bdfLive = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfLive, "Live","Active?");
grdExisting.Columns.Add(bdfPrivName);
grdExisting.Columns.Add(bdfDescription);
grdExisting.Columns.Add(bdfLive);
I then use FindControl() to locate the checkbox and textboxes and perform my logic based the result
foreach (GridViewRow gvr in grdMissing.Rows)
{
mckbAny = (CheckBox)gvr.FindControl("ckbAdd");
mtxtApplyDate = (TextBox)gvr.FindControl("txtAddApplyDate");
mtxtDateToAdd = (TextBox)gvr.FindControl("txtAddDateToAdd");
mtxtDateToRemove = (TextBox)gvr.FindControl("txtAddDateToRemove");
}
etc.
This all worked fine. I then got a request to put the bound fields as the second, third and fourth columns, after the check box and before the textboxes. I found that this was easy to do by changing the Add’s to Inserts as follows:
grdExisting.Columns.Insert(1, bdfPrivName);
grdExisting.Columns.Insert(2, bdfDescription);
grdExisting.Columns.Insert(3, bdfLive);
It looked fine of the page, but the FindControl(), all of them fail to work.
Please suggest a solution or a workaround.
Thanks in advance.
It sounds like you have come across this bug:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104994&wa=wsignin1.0
It appears ViewState is not stored (or restored) when a BoundField is inserted into a GridView. So when you do FindControl it doesn't exist.
You could try adding them as you did before and finding some way of re-arranging the columns (I think this is possible).
I am not sure how it was working for you before, as controls don't belong in row - they are inside cells. Anyways, the issue is that FindControl is not recursive, it will not search entire control tree - only immediate children of the control you run it on. You need to implement your own recursive findcontrol, for example like so:
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control c in Root.Controls)
{
Control fc = FindControlRecursive(c, Id);
if (fc != null)
return fc;
}
return null;
}

Categories