Thursday, May 20, 2010

Method to get values from controls by name

Use this method to get the values from controls on a form by passing in
the ID of the control, like this:

string test = ControlValue(textbox1);

ControlValue code:

public string ControlValue(string controlName)
{
string value = "";
Control c = FindControl(controlName);
if (c is DropDownList)
{
value = ((DropDownList)c).SelectedValue;
}
else if (c is TextBox)
{
value = ((TextBox)c).Text;
}
else if (c is Label)
{
value = ((Label)c).Text;
}
else if (c is ListBox)
{
string list = ",";
foreach (ListItem li in ((ListBox)c).Items)
{
if (li.Selected)
{
list += "," + li.Value;
}
}
value = list.Replace(",,", "");
}
return value;
}

No comments: