i am trying to find the value of checked radio using group name i have method that return it but what should i pass in that method along with group name
method is here,
private string getRadioValue(ControlCollection clts, string groupName)
{
string ret = "";
foreach (Control ctl in clts)
{
if (ctl.Controls.Count != 0)
{
if (ret == "")
ret = getRadioValue(ctl.Controls, groupName);
}
if (ctl.ToString() == "System.Web.UI.WebControls.RadioButton")
{
RadioButton rb = (RadioButton)ctl;
if (rb.GroupName == groupName && rb.Checked == true)
ret = rb.Attributes["Value"];
}
}
return ret;
}
i use it like
Oc.aProjectSubmited = getRadioValue(RadioButton,"Aps");
where Aps is radio group but getting error "invalid argument" on radio button i pass ??
hopes for your suggestion thanks in advance
This is because you are passing RadioButton. Your method accepts ControlCollection, not a Control.
Why not pass this.Controls to pass the whole ControlCollection of the page? Or any other ControlCollection that you might be using to keep that RadioButton you want to check?
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
getRadioValue(this.Controls, "Hello");
}
private string getRadioValue(ControlCollection clts, string groupName)
{
string ret = "";
foreach (Control ctl in clts)
{
if (ctl.Controls.Count != 0)
{
if (ret == "")
ret = getRadioValue(ctl.Controls, groupName);
}
if (ctl.ToString() == "System.Web.UI.WebControls.RadioButton")
{
RadioButton rb = (RadioButton)ctl;
if (rb.GroupName == groupName && rb.Checked == true)
ret = rb.Attributes["Value"];
}
}
return ret;
}
Here's a shorter version using Linq to avoid the loops...
public static string GetRadioValue(ControlCollection controls, string groupName)
{
var selectedRadioButton = controls.OfType<RadioButton>().FirstOrDefault(rb => rb.GroupName == groupName && rb.Checked);
return selectedRadioButton == null ? string.Empty : selectedRadioButton.Attributes["Value"];
}
Use LINQ:
container.Controls.OfType<RadioButton>().FirstOrDefault(r => r.GroupName == "GroupName" && r.Checked).Text;
The ToString() is not going to give you what you want: You need somthing more like
private string getRadioValue(ControlCollection clts, string groupName)
{
var ret = "";
foreach (Control ctl in clts)
{
if (ctl.Controls.Count != 0)
{
ret = getRadioValue(ctl.Controls, groupName);
}
if (!string.IsNullOrEmpty(ret)) {
return ret;
}
var rb = ctl as RadioButton;
if (rb != null && rb.GroupName == groupName && rb.Checked)
return = rb.Attributes["Value"];
}
}
return ret;
}
Even more shorter version (in my example I needed the Text of the Radio) Button.
You can also make it as an extension method of HtmlGenericControl which would be div for example.
public static class HtmlGenericControlExtensions
{
/// <summary>
/// Gets selected value of radio button by group name.
/// </summary>
/// <param name="controls">Html generic control.</param>
/// <param name="groupName">Name of the button group.</param>
/// <returns>Selected radio button name.</returns>
public static string GetSelectedRadioButtonName(this HtmlGenericControl control, string groupName)
=> control.Controls
.OfType<RadioButton>()
.FirstOrDefault(rb => rb.GroupName.Equals(groupName) && rb.Checked)?.Text ?? string.Empty;
}
Related
I have a DropDownList control which really don't want to enable ViewState for as the item list is readily available from the server.
In this situation a post-back will obviously show an empty Items list, but at the same time I want the SelectedIndexChanged event to fire (using AutoPostBack)
The DropDownList control is actually dynamically created as part of a Composite Control which created an arbitrary number of DDLs - some of whose Items are sourced from the ASPX file (composite control contents) and others whose Items are bound to a data source. I am hoping that this complication isn't the source of the problem.
My thinking is that I should bind the list data to the Items collection on initial PageLoad and also rebind it late on PostBacks but I am not sure when. I am also not sure if the SelectedIndexChanged event handler will get called if on PostBack there is an empty Items list again.
Because it is part of a CompositeControl, I wonder if I should store some additional information in Control State. Would implementing something in the Conposite Control's Save/LoadControlState, Save/LoadViewState, RaisePostDataChangedEvent or RaisePostbackEvent be the solution?
Maybe I should rebind the Item list again early on PostBack e.g.before PageLoad?
Any pointers will be appreciated.
Thanks
Code provided below (cut out most of what is not relevant to problem)
Page ASPX
Note that I want to populate the ListItems of the { Group, Location, Division and BusinessUnit } DropDownLists dynamically with the items not being in dumped to ViewState but { Enabled } DDL is the static items defined below.
<cc1:FilterBar ID="FilterBar1" runat="server" CssClass="filterbar" OnFilterChanged="OnFilterChanged">
<cc1:Filter ID="Group" Label="Group" Type="DropDownList" />
<cc1:Filter ID="Location" Label="[Location]" Type="DropDownList" />
<cc1:Filter ID="Division" Label="[Division]" Type="DropDownList" />
<cc1:Filter ID="BusinessUnit" Label="[Business Unit]" Type="DropDownList" />
<cc1:Filter ID="Enabled" Label="Users" Type="DropDownList">
<asp:ListItem Value="X" Text="All"></asp:ListItem>
<asp:ListItem Value="1" Text="Active Only"></asp:ListItem>
<asp:ListItem Value="0" Text="Archived Only"></asp:ListItem>
</cc1:Filter>
</cc1:FilterBar>
Page Code Behind
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack) // whether to restire BindFilterBar() to first load or not?
BindFilterBar();
}
protected void BindFilterBar()
{
var h = new FilterBarBindHelper(FilterBar1);
h.AutoBindLocation(Filter.UserLocation.ID);
h.AutoBindDivision(Filter.UserDivision.ID);
h.AutoBindBusinessUnit(Filter.UserBusinessUnit.ID);
h.AutoBindGroup(Filter.UserGroup.ID);
var filter = FilterBar1.GetFilterByID("Enabled");
filter.SelectedValue = Filter.UserEnabledAsChar.ToString();
}
protected void OnFilterChanged(object sender, FilterChangedEventArgs e)
{
Debug.WriteLine($"[CompletionResults.aspx] OnFilterChanged(e={{FilterID={e.FilterID}; NewValue={e.NewValue} NewText={e.NewText}}})");
switch(e.FilterID)
{
case "Enabled":
Filter.UserEnabledAsChar = e.NewValue;
break;
case "Group":
if (e.NewValueAsInt == null)
Filter.UserGroup.Reset();
else
Filter.UserGroup.Set((int)e.NewValueAsInt, e.NewText);
break;
case "Division":
if (e.NewValueAsInt == null)
Filter.UserDivision.Reset();
else
Filter.UserDivision.Set((int)e.NewValueAsInt, e.NewText);
break;
case "BusinessUnit":
if (e.NewValueAsInt == null)
Filter.UserBusinessUnit.Reset();
else
Filter.UserBusinessUnit.Set((int)e.NewValueAsInt, e.NewText);
break;
case "Location":
if (e.NewValueAsInt == null)
Filter.UserLocation.Reset();
else
Filter.UserLocation.Set((int)e.NewValueAsInt, e.NewText);
break;
default:
return;
}
// Update Selection Text
BindSelectionText();
// Update the Grid
BindGrid();
}
/// <summary>
/// User has selected a new Page number from the UserGrid
/// </summary>
protected void OnPageChanged(object sender, EventArgs args)
{
Filter.ShowAllRows = false;
Filter.PageIndex = UserGrid.PageIndex;
BindGrid();
}
protected void OnAction(object sender, ToolbarActionClickedEventArgs args)
{
if (args.ActionValue == "email")
OnEmail();
}
FilterBarBindHelper.cs
public class FilterBarBindHelper
{
private readonly FilterBar _filterBar;
private readonly OrganisationProperties _orgProps;
public FilterBarBindHelper(FilterBar filterBar)
{
if (filterBar == null)
throw new ArgumentNullException(nameof(filterBar));
_filterBar = filterBar;
_orgProps = ObjectCache.GetOrganisationProperties();
}
/// <summary>
/// Binds Group list data to Filter, optionally creating the Filter if it doesn't exist
/// </summary>
/// <param name="selectedID">ID of currently selected Group to filter by (0 or null if none)</param>
/// <param name="createFilter">Create the Filter if not found</param>
public void AutoBindGroup(int? selectedID, bool createFilter = true)
{
// All Organisations have Groups.
// Only populate if a FilterBar Filter with ID="Groups" can be found or if createFilter = true
var f = _filterBar.GetFilterByID("Group");
if (f == null)
if (createFilter)
f = CreateFilter("Group", "Group");
else
return;
// Populate Filter list with items
var src = GroupCache.Get();
f.Items.Clear();
f.Items.Add(Any());
f.Items.AddRange(src.Select(s => new ListItem() { Value = s.StringID, Text = s.Name }).ToArray());
// Assign localised name
f.Label = _orgProps.GroupNm;
// Select
if((selectedID ?? 0) != 0)
f.SelectedValue = selectedID.Value.ToString();
_filterBar.RefreshFilter(f);
}
/// <summary>
/// Create a FilterBar Filter and add it to the FilterBar
/// </summary>
/// <param name="filterID">ID of filter to add</param>
/// <param name="label">Filter's label</param>
/// <param name="type">Filter's type</param>
/// <returns>New Filter</returns>
private Filter CreateFilter(string filterID, string label, FilterType type = FilterType.DropDownList)
{
var f = new Filter() { ID = filterID, Type = type, Label = label };
_filterBar.Filters.Add(f);
return f;
}
private ListItem Any()
{
return new ListItem("Any", "X");
}
}
Toolbar.cs
[
AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
DefaultProperty("Items"),
ParseChildren(true, "Items"),
ToolboxData("<{0}:Toolbar runat=server />"),
Designer(typeof(ToolbarDesigner))
]
public class Toolbar : CompositeControl
{
private string _preText = "Actions: ";
private bool _showRight = true;
private readonly List<ToolbarItem> _list = new List<ToolbarItem>();
public Toolbar()
{
PreText = "Actions: ";
ObjectNameSingle = "Item";
ObjectNamePlural = "Items";
ShowRight = true;
}
protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } }
[
Category("Behavior"),
Description("The Item collection"),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
Editor(typeof(ToolbarCollectionEditor), typeof(UITypeEditor)),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public List<ToolbarItem> Items
{
get { return _list; }
}
//various properties (snip)
protected override void RenderContents(HtmlTextWriter writer)
{
if(_leftSide != null)
_leftSide.RenderControl(writer);
if(_rightSide != null)
_rightSide.RenderControl(writer);
if(_leftSide == null && _rightSide == null && DesignMode)
writer.Write("No Toolbar Items have been set up in designer");
}
public void RebuildChildControls()
{
// Indicate that the child controls need rebuilding
// Ref: http://yourdotnetdesignteam.blogspot.co.uk/2008/09/life-cycle-of-aspnet-controls_28.html "Composite Controls" section:
// "Note 1: When the Composite Control is displayed normally, 'CreateChildControls' is called AFTER the 'Load' method.
// However, when a post back event occurs, 'CreateChildControls' is called AFTER the 'Init' method.
// This certainly makes the 'CreateChildControls' method an "interesting" aspect of the Life Cycle."
// So on postback, the calling method should call RebuildChildControls() after repopulating/modifying Filter Items
ChildControlsCreated = false;
//RecreateChildControls(); this will happen in due course anyway
}
// Controls in Composite Control
private ToolbarActionContainer _leftSide;
private WebControl _rightSide;
private ToolbarActionItem _liPreText;
private Literal _litPreText;
private HtmlGenericControl _spanRowCount;
private HtmlGenericControl _spanPageCount;
private DropDownList _ddlPage;
private Literal _litPageCount;
protected override void CreateChildControls()
{
Controls.Clear();
_leftSide = new ToolbarActionContainer(); // UL
_rightSide = new WebControl(HtmlTextWriterTag.Div);
_liPreText = new ToolbarActionItem(ToolbarActionType.PreText);
_litPreText = new Literal() { Text = "Actions: " };
// Create the Toolbar Action Items
var actionItems = new List<ToolbarActionItem>(_list.Count);
foreach (var item in _list)
{
if (item.Visible)
{
var li = CreateToolbarActionItemControls(item);
actionItems.Add(li);
}
}
_spanRowCount = new HtmlGenericControl("span"); // "NNN entitie(s) found";
_spanPageCount = new HtmlGenericControl("span"); // "Page [DDL] of [LIT]";
_ddlPage = new DropDownList() { ID = "PageDDL", AutoPostBack = true, EnableViewState = false };
_litPageCount = new Literal();
_spanPageCount.Controls.Add(new Literal() { Text = "Page " });
_spanPageCount.Controls.Add(_ddlPage);
_spanPageCount.Controls.Add(new Literal() { Text = " of " });
_spanPageCount.Controls.Add(_litPageCount);
_liPreText.Controls.Add(_litPreText);
_leftSide.Controls.Add(_liPreText);
foreach(var item in actionItems)
_leftSide.Controls.Add(item);
_rightSide.Controls.Add(_spanRowCount);
_rightSide.Controls.Add(_spanPageCount);
Controls.Add(_leftSide);
Controls.Add(_rightSide);
_ddlPage.SelectedIndexChanged += PageDDL_SelectedIndexChanged;
base.CreateChildControls();
ChildControlsCreated = true;
UpdateRowCountText(); // Assigns the RowCount text to the span control _spanPageCount
UpdatePageCountText(); // The Y in "Page X of Y"
ApplyStandardClassNames();
CreatePageDDLItems(); // Populates Items in PageDDL (if required)
AssignPageDDLSelectedValue(); // Assigns the current PageDDL value (if required)
}
protected virtual ToolbarActionItem CreateToolbarActionItemControls(ToolbarItem item)
{
// Create List Item and add CssClass if required
var li = CreateToolbarActionItem(ToolbarActionType.Action);
if (item.HasCssClass)
li.CssClass = item.CssClass;
if (item.TextOnly)
{
// Text Only Action Items are added as literal text
li.Controls.Add(new Literal() { Text = item.Text });
}
else
{
var btn = new LinkButton() { Text = item.Text, ToolTip = item.ToolTip, CssClass = item.CssClass };
if (item.HasURLLink)
btn.Attributes.Add("href", item.URLLink);
else
{
btn.Click += LinkButton_Clicked;
_map.Add(btn, item); // used if posting back
// btn.Attributes.Add("href", "#");
// var js = MakeButtonJavaScript(item);
// if (js != string.Empty)
// btn.Attributes.Add("onclick", "javascript:" + js);
if(!string.IsNullOrEmpty(item.PrePostbackJSFunction))
btn.OnClientClick = $"return {item.PrePostbackJSFunction}(this);";
}
li.Controls.Add(btn);
}
return li;
}
protected virtual ToolbarActionItem CreateToolbarActionItem(ToolbarActionType type)
{
return new ToolbarActionItem(type);
}
private void CreatePageDDLItems()
{
// No DDL control created yet?
if (!ChildControlsCreated)
return;
var pageCount = PageCount;
// Current count is already correct?
if (pageCount == _ddlPage.Items.Count - 1) // -1 = "all"
return;
_ddlPage.Items.Clear();
_spanPageCount.Visible = (pageCount > 1); // Show this section only if multipage
// Not multi page?
if (pageCount <= 1)
return;
var li = new ListItem("All", "all");
_ddlPage.Items.Add(li);
for (var i = 0; i < pageCount; i++)
{
li = new ListItem((i + 1).ToString());
_ddlPage.Items.Add(li);
}
// AssignPageDDLSelectedValue() is already called whenever CreatePageDDLItems() is called!
//AssignPageDDLSelectedValue();
}
private void AssignPageDDLSelectedValue()
{
if (!ChildControlsCreated)
return;
if (ShowAllPages)
_ddlPage.SelectedValue = "all";
else
_ddlPage.SelectedValue = CurrentPage.ToString();
}
private void LinkButton_Clicked(object sender, EventArgs e)
{
System.Diagnostics.Debug.Assert(sender is LinkButton);
var button = sender as LinkButton;
var item = _map[button];
// Raise event with item's value
OnActionButtonClicked(item.Value);
}
private void PageDDL_SelectedIndexChanged(object sender, System.EventArgs e)
{
System.Diagnostics.Debug.Assert(sender == _ddlPage);
var v = _ddlPage.SelectedValue;
var newShowAllPages = (v == "all");
var newPage = newShowAllPages ? 0 : int.Parse(v);
// No Change?
if (newShowAllPages == ShowAllPages &&
(!newShowAllPages && (newPage == CurrentPage)))
return;
// Assign and raise event
ShowAllPages = newShowAllPages;
CurrentPage = newPage;
OnPageChanged(newShowAllPages, newPage);
}
private void OnActionButtonClicked(string id)
{
var evt = ActionClicked;
// check there are subscribers, and trigger if necessary
if (evt != null)
evt(this, new ToolbarActionClickedEventArgs(id));
}
private void OnPageChanged(bool showAll, int newPageNumber)
{
var evt = PageChanged;
// check there are subscribers, and trigger if necessary
if (evt != null)
evt(this, new ToolbarPageChangedEventArgs(showAll, newPageNumber));
}
}
public class ToolbarPageChangedEventArgs : EventArgs
{
public bool ShowAllPages { get; }
public int NewPageNumber { get; }
internal ToolbarPageChangedEventArgs(bool showAllPages, int newPageNumber)
{
ShowAllPages = showAllPages;
NewPageNumber = newPageNumber;
}
}
public class ToolbarActionClickedEventArgs : EventArgs
{
public string ActionValue { get; }
internal ToolbarActionClickedEventArgs(string value)
{
ActionValue = value;
}
}
public delegate void ToolbarPageChangedEventHandler(object sender, ToolbarPageChangedEventArgs args);
public delegate void ToolbarActionClickedEventHandler(object sender, ToolbarActionClickedEventArgs args);
ToolbarItem.cs
[TypeConverter(typeof(ExpandableObjectConverter))]
public class ToolbarItem
{
public ToolbarItem() : this(string.Empty, string.Empty, string.Empty, string.Empty)
{
}
public ToolbarItem(string text, string value, string jslink, string urllink)
{
Text = text;
Value = value;
JSLink = jslink;
URLLink = urllink;
CssClass = string.Empty;
ToolTip = string.Empty;
PrePostbackJSFunction = string.Empty;
Visible = true;
}
.... snip ...
}
public enum ToolbarActionType
{
None = 0,
PreText = 1,
Action = 2,
}
I want to add runat=server dynamically to a CheckBoxList so that it can be found by FindControl.
CheckBoxList cbl = new CheckBoxList();
cbl.ID = "cbl" + intQuestionCount.ToString();
// get choices from choice list
int intChoiceListId = Convert.ToInt32(detail.ChoiceListID);
var choiceList = (from cl in _svsCentralDataContext.SVSSurvey_ChoiceListItems
where cl.ChoiceListID == intChoiceListId
orderby cl.Description
select cl);
cbl.DataSource = choiceList;
cbl.DataTextField = "Description";
cbl.DataBind();
cbl.Visible = true;
cbl.CssClass = "PositionCol3";
questionsPanel.Controls.Add(cbl);
I have 2 recursive find control methods:
private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase)
&& childControl is HtmlControl
)
{
return (HtmlControl)childControl;
}
if (childControl.HasControls())
{
HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
if (result != null)
{
return result;
}
}
}
return null;
}
private WebControl FindWebControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase)
&& childControl is WebControl
)
{
return (WebControl)childControl;
}
if (childControl.HasControls())
{
WebControl result = FindWebControlByIdInControl(childControl, id);
if (result != null)
{
return result;
}
}
}
return null;
}
The screen is initially created dynamically (if !isPostback), based on an SQL record. The FindControl methods are used after this lot has been displayed, when the user clicks the 'Save' button.
Neither Find control method finds my CheckBoxList!!
You are adding controls through your code behind, they are already server side controls, you don't have to add runat="server". You are not finding them properly.
Make sure they are added to the page before you look for them.
I want to get all the control from multiple form (Main, Two and Three) and
compare if the control tag equals the variable str_name and if true write the
value of str_value in c.Text.
the code:
private static Form[] getformular()
{
Main main = new Main();
Two f2 = new Two();
Three f3 = new Three();
Form[] form = { main, f2, f3};
return form;
}
private void initcontrol()
{
String str_name = "name";
String str_value = "value";
foreach(Form f in getformular())
{
foreach (Control c in f.Controls)
{
if (f != null && c = null)
{
if (c.Tag.Equals(str_name))
{
c.Text = str_value;
}
}
}
}
}
Could please someone help me?
First, as stated by #JonB some of conditional checking (ifs logic) in your current code seems off.
Second, looping through Form.Controls will only bring you all controls placed directly in the Form. For example if you have tab control (or any other container control) placed in form, and you have a textbox inside that tab control, you'll get only the tab control and couldn't find the textbox by looping through Form.Controls. You can solve that with recursive method as demonstrated below.
private void initcontrol()
{
String str_name = "name";
String str_value = "value";
var result = false;
foreach(Form f in getformular())
{
//if you want to check if f null, it should be here.
if(f != null) result = setControlText(f, str_name, str_value);
}
if(!result) MessageBox.Show("Control not found");
}
private bool setControlText(Control control, string str_name, string str_value)
{
var isSuccess = false;
foreach (Control c in control.Controls)
{
//if c is not null
if (c != null)
{
//check c's Tag, if not null and matched str_name set the text
if (c.Tag != null && c.Tag.Equals(str_name))
{
c.Text = str_value;
isSuccess = true;
}
//else, search in c.Controls
else isSuccess = setControlText(c, str_name, str_value);
//if control already found and set, exit the method now
if (isSuccess) return true;
}
}
return isSuccess;
}
I have a problem in code in C#:
I don't know how to implement logic - iterating through Hashtable
having values of different data types, the schema I want is below:
if the value in variable is String type
{
do action1;
}
else
{
do action2;
}
There is a hashtable containing data of Types - String and Int (combined):
public string SQLCondGenerator {
get
{
Hashtable conditions = new Hashtable();
//data having String data type
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
conditions.Add("materialdescription", ViewState["mat_desc_txt"]);
conditions.Add("suppliername", ViewState["supplier_txt"]);
conditions.Add("manufacturername", ViewState["manufacturer_txt"]);
//data having Int32 data type
conditions.Add("spareparts", ViewState["sp_id"]);
conditions.Add("firstfills", ViewState["ff_id"]);
conditions.Add("specialtools", ViewState["st_id"]);
conditions.Add("ps_deleted", ViewState["ps_del_id"]);
conditions.Add("po_manuallyinserted", ViewState["man_ins_id"]);
String SQLCondString = "";
String SQLCondStringConverted = "";
string s = string.Empty;
foreach (string name in conditions.Keys)
{
if (conditions[name] != null)
{
SQLCondString += name+ "=" +conditions[name]+ " and ";
Response.Write(conditions[name].GetType());
bool valtype = conditions[name].GetType().IsValueType;
if (valtype == string)
{
SQLCondString.Substring(0, SQLCondString.Length - 4);
SQLCondString += name + " and like '%" + conditions[name] + "%' and ";
}
}
}
//Response.Write("********************");
SQLCondStringConverted = SQLCondString.Substring(0, SQLCondString.Length - 4);
return SQLCondStringConverted;
}
}
May be I am wrong in coding, please advise!
Thanks!
if(conditions[name] is string)
{
}
else
{
}
Hmm, I'm not sure why you are calling IsValueType, but this should be sufficient:
if (conditions[name] is string)
{
///
}
Approach - 1
Int32 Val = 0;
if (Int32.TryParse("Your Value", out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
Approach - 2 (using Late Binding)
Int32 Val = 0;
dynamic conditions = new Hashtable();
conditions.Add("miap", ViewState["miap_txt"]);
conditions.Add("pocode", ViewState["po_txt "]);
foreach (string name in conditions.Keys)
{
if (Int32.TryParse(conditions[name].ToString(), out Val))
{
//Your Logic for int
}
else
{
//Your Logic for String
}
}
I had the same issue but I was using textBoxes and needed to validate if the input is alphabets,-, or .
I generated a keypress event on my textBox and inserted the following method to check each keypress and give a prompt if its not a valid character:
public static class Validator
{
public static bool IsNameString(TextBox tb, string name, KeyPressEventArgs e)
{
bool valid = true;
/* e.KeyChar contains the character that was pressed
e.Handled is a boolean that indicates that handling is done
if a bad character is entered, set e.Handled to true
*/
if (!char.IsLetter(e.KeyChar) && e.KeyChar != ' ' && e.KeyChar != '-' &&
e.KeyChar != '.' && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
valid = false;
MessageBox.Show(name+ " can only accept letters, space, - and .");
tb.Focus();
}
return valid;
}
}
usage:
private void txtCustomerName_KeyPress(object sender, KeyPressEventArgs e)
{
Validator.IsNameString(txtCustomerName, "Customer Name", e);
}
I am coding a function which will take a Control Ctrl as Arguement and Modify the Control.Content of it.
Is there Any way to Get and Set the Content of any Control??
Code :
void RemoveHotKey(Control Ctrl, int KeyIndex)
{
if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_") // System.Windows.Controls.Control does not contain a definition for 'Content'
{
Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1); // System.Windows.Controls.Control does not contain a definition for 'Content'
}
}
try this instead:
void RemoveHotKey(ContentControl Ctrl, int KeyIndex)
{
if (Ctrl.Content.ToString().Substring(KeyIndex, 1) == "_")
{
Ctrl.Content = Ctrl.Content.ToString().Remove(KeyIndex, 1);
}
}
take a look here.
or this:
void RemoveHotKey(Control Ctrl, int KeyIndex)
{
ContentControl contentCtrl = Ctrl as ContentControl;
if (contentCtrl != null && contentCtrl.Content != null)
{
if (contentCtrl.Content.ToString().Substring(KeyIndex, 1) == "_")
{
contentCtrl.Content = contentCtrl.Content.ToString().Remove(KeyIndex, 1);
}
}
}
which is way less expensive than using reflection..
You could change the signature of your method to this:
void RemoveHotKey(ContentControl Ctrl, int KeyIndex)
a ContentControl always has a Content property.
You could use reflection to check whether Control in fact has a Content property...
Type t = Ctrl.GetType();
PropertyInfo p = t.GetProperty("Content");
if (p != null)
{
string val = p.GetValue(Ctrl, null) ?? "";
val = val.Replace("_", "");
p.SetValue(Ctrl, val, null);
}