How to get Control Value Form Control ID asp.net C#? - c#

I have my page fills controls dynamically So All I can get is Control ID
So how can I get control Value or name from control ID
I tried this but nothing I get
TextBox control = new TextBox { ID = _NumberFieldID + item.BlueprintFieldId, CausesValidation = true, EnableViewState = true, CssClass = "form-control ui-spinner-input spin metadatacontrol", Width = new Unit(ctrWidth + "%") };
ctrlDivSet.Controls.Add(control);
and that is my experiment
Control ControlValues= FindControl(_NumberFieldID + validationObject.MatchBlueprintFieldId);
I tried to compare two controls values
So I used this
CompareValidator controlValidator = new CompareValidator()
{
ControlToValidate = control.ID,
ControlToCompare = _NumberFieldID + validationObject.MatchBlueprintFieldId,
Operator = voperator,
ValidationGroup = _ValidationGroup,
};
CotrolTOCompare can take the ID and compare its value
I need somthing like that
to obtain control name or value by its ID
please help

Im a bit confused as to what you want so let's start from here and then I'll update to address if it's not correct :)
To get a value you can use in for ex. JavaScript you can do
var clientId = myTextBox.ClientId;
If you want to use the name to get the control
var textBox = (TextBox)FindControl("myTextBox");

Related

Getting the "value" property of a control

I have a method that has a Control parameter. I want to get the value of the control. So if it is a TextBox get the value of the Text property; if it is a NumericUpDown get the value of the Value property and so on.
The problem is that I cannot write something like this:
Method(Control control)
{
control.Text;
}
or
Method(Control control)
{
control.Value;
}
Because there is no guarantee that the control has one of these properties, and what is its name if it does have it.
Is there a way to do something like that?
There isn't such common Value property in Control class.
You should use some if/else or switch/case or a dictionary approach to get the value from the control. Because you know what property you need. The control just provides properties.
For example for a ComboBox, what is the value? Is it SelectedItem, SelectedIndex, SelectedValue, Text? It's usage/opinion based.
The nearest thing to what you are looking for, is relying on DefaultProperty attribute of controls to get the value from that property using relfection. For example, having this method:
public object GetDefaultPropertyValue(Control c)
{
var defaultPropertyAttribute = c.GetType().GetCustomAttributes(true)
.OfType<DefaultPropertyAttribute>().FirstOrDefault();
var defaultProperty = defaultPropertyAttribute.Name;
return c.GetType().GetProperty(defaultProperty).GetValue(c);
}
You can get values this way:
var controls = new List<Control> {
new Button() { Text = "button1" },
new NumericUpDown() { Value = 5 },
new TextBox() { Text = "some text" },
new CheckBox() { Checked = true }
};
var values = controls.Select(x => GetDefaultPropertyValue(x)).ToList();

C# how to get HTML controls created dynamically

I generated a HTMLTextArea using string and Response.Write():
string area = "<textarea id=\"myArea{0}\" cols=\"30\" name=\"S1\" rows=\"5\" runat=\"server\"></textarea>";
Response.Write(String.Format(area,1));
After this, I don't know how to get the object of this myArea1.
Are there any way I can achieve this goal?
The proper way to add System.Web.UI.HtmlControls. will be,
var newTextArea = new HtmlTextArea()
{
ID = string.Format("myArea{0}", 1),
Name = string.Format("S{0}", 1),
Cols = 30,
Rows = 5
};
Page.Controls.Add(newTextArea);
Then you can access it like,
var myTextArea = Page.FindControl("myArea1") as HtmlTextArea;
You can try this.
HtmlTextArea txt = (HtmlTextArea)(Page.FindControl("myArea1"));
string value = txt.Value;
Refer to this.
You don't really need to access the TextArea object itself if you are only interested in getting the user input, which you should be able to find in Request.Form collection on form submission.

Capture value of Textbox when OnChange is defined in the textbox

I have a dynamically generated grid with x number of textboxes that will be in it. As each textbox is generated, I give it an OnChange event that is a set function.
Html.TextBox(... new { #onchange = "ChangeItemQuantity(" + vm.ID + ", " + fk.id + ")" ...
So when it's rendered, it looks like this:
<input ... type="text" onchange="ChangeItemQuantity(1939, 3)" />
Then, in the script section:
function ChangeItemQuantity(ItemId, ForeignKeyId) {
...
}
In the ChangeItemQuantity() function, how would I also capture the new value of the textbox? I don't really want to use an id on the textbox, because it is part of a grid with many textboxes.
Should I pass it in as a parameter? If so, what would the syntax be of the code that renders the textbox?
Or, is there a way to capture is inside the javascript function?
Thanks!
If you want to store data in the html element why not use data- attributes?
Set them like so
#Html.TextBox(.... new { #class="someClass" data-vmId="vm.ID", data-fkId="fk.id" })
Then set a listener on that class
$('.someClass').change(function() {
var value = $(this).val();
var vmid = $(this).data('vmid');
var fkid = $(this).data('fkid');
}

How to set selectedValue to Controls.Combobox in c#?

I have a combobox and I see that I am not able to set SelectedValue like this:
cmbA.SelectedValue = "asd"
So I tried to do this
cmbA.SelectedIndex = cmbA.FindString("asd");
Based on How to set selected value from Combobox?
I realised that my combobox is a System.Windows.Controls.ComboBox and not a System.Windows.Forms.ComboBox.
That means that FindString() is not available.
Based on User Control vs. Windows Form I get that forms are the container for controls, but I dont get why the Controls.ComboBox does not implement FindString().
Do I have to write my own code to do what FindString() does for Forms.ComboBox?
WPF ComboBoxes are not the same as WinForms ones. They can display a collection of objects, instead of just strings.
Lets say for example if I had
myComboBox.ItemsSource = new List<string> { "One", "Two", "Three" };
I could just use the following line of code to set the SelectedItem
myComboBox.SelectedItem = "Two";
We're not limited to just strings here. I could also say I want to bind my ComboBox to a List<MyCustomClass>, and I want to set the ComboBox.SelectedItem to a MyCustomClass object.
For example,
List<MyCustomClass> data = new List<MyCustomClass>
{
new MyCustomClass() { Id = 1, Name = "One" },
new MyCustomClass() { Id = 2, Name = "Two" },
new MyCustomClass() { Id = 3, Name = "Three" }
};
myComboBox.ItemsSource = data;
myComboBox.SelectedItem = data[0];
I could also tell WPF I want to consider the Id property on MyCustomClass to be the identifying property, and I want to set MyCombbox.SelectedValue = 2, and it will know to find the MyCustomClass object with the .Id property of 2, and set it as selected.
myComboBox.SelectedValuePath = "Id";
myComboBox.SelectedValue = 2;
I could even set the Display Text to use a different property using
myComboBox.DisplayMemberPath = "Name";
To summarize, WPF ComboBoxes work with more than just Strings, and because of the expanded capabilities, FindString is not needed. What you are most likely looking for is to set the SelectedItem to one of the objects that exist in your ItemsSource collection.
And if you're not using ItemsSource, then a standard for-each loop should work too
foreach(ComboBoxItem item in myComboBox.Items)
{
if (item.Content == valueToFind)
myComboBox.SelectedItem = item;
}
I don't know what you are trying to do but I think it would be easier to just do
cmbA.Text = "String";
That way you get your selected item
Else I found an intersting article that could help you out:
Difference between SelectedItem, SelectedValue and SelectedValuePath

Dynamically Generated Dropdowns Postback

I'm having some trouble with same Dynamically generated dropdowns and their viewstate.
Long story short, a user will upload an excel file, the file will get parsed and the dropdowns will be created for the appropriate data. This is done on when an asp button is pressed, and the controls are added to a table as follows:
public void generateFromSheet(OrderedDictionary columns, DataTable oppcolumns, List<string> requiredDrops)
{
int index = 0;
foreach (DictionaryEntry entry in columns)
{
DropDownList ddl = new DropDownList()
{
ID = "ddlMapping" + entry.Key.ToString(),
DataSource = columns,
DataTextField = "Key",
DataValueField = "Value",
SelectedIndex = index,
Enabled = requiredDrops.Contains(entry.Key) ? false : true
};
ddl.DataBind();
DropDownList ddl2 = new DropDownList()
{
ID = "OpportunityMappingDdl" + index,
DataSource = oppcolumns,
DataTextField = "AttributeDisplayName",
DataValueField = "TableColumnName"
};
ddl2.DataBind();
HtmlTableCell td = new HtmlTableCell()
{
ID = "tdMapping" + index
};
td.Controls.Add(ddl);
HtmlTableCell td2 = new HtmlTableCell()
{
ID = "tdOppMapping" + index
};
td2.Controls.Add(ddl2);
HtmlTableRow tr = new HtmlTableRow()
{
ID = "trMapping" + index
};
tr.Cells.Add(td);
tr.Cells.Add(td2);
tblFileMapping.Rows.Add(tr);
index++;
}
}
However, on each postback after this, the drop-downs are erased. I've looked online for a solution and usually everything points to recreating the controls using the same id's as when they were created so that their state can be restored from ViewState. I've tried that as follows below by storing what I should create in ViewState:
public void generateFromViewState()
{
OrderedDictionary columns = (OrderedDictionary) ViewState["XLColumns"];
int index = 0;
foreach (DictionaryEntry entry in columns)
{
DropDownList ddl = new DropDownList()
{
ID = "ddlMapping" + entry.Key.ToString(),
};
DropDownList ddl2 = new DropDownList()
{
ID = "OpportunityMappingDdl" + index,
};
HtmlTableCell td = new HtmlTableCell()
{
ID = "tdMapping" + index
};
td.Controls.Add(ddl);
HtmlTableCell td2 = new HtmlTableCell()
{
ID = "tdOppMapping" + index
};
td2.Controls.Add(ddl2);
HtmlTableRow tr = new HtmlTableRow()
{
ID = "trMapping" + index
};
tr.Cells.Add(td);
tr.Cells.Add(td2);
tblFileMapping.Rows.Add(tr);
index++;
}
}
I call this method in the page_load but the controls do not retain their previous data and selected values.
So a couple of things wrong here:
On page_load the controls are recreated but their state is not restored.
For some technical reasons, my Project Manager mentioned I should not use the Session State to store anything.
Another PM advised me that the controls should be regenerated on page_init. BUT since I'm storing the control data in ViewState, this isn't possible because the viewstate isnt ready and my data is null.
Can anyone advise on how to succesfully restore the viewstate for these dynamically generated controls. I've tried searching everything and tried a bunch of solutions online, but nothing I have tried seems to work.
Thanks!
You are doing it right, but you have to recreate the controls with datasource and rebinding all controls again. Without this beeing done, you are creating controls that not match the previous. You can call your first method to do that.

Categories