C# converting String to HtmlControl data type

992 Views Asked by At

I am dynamically populating the ID of a textbox which is saved in my database. I am setting it as a string when pulling the value out of a data set which determines the parameters for a search.

I now want to use the string parameter as the dynamic ID for an Attributes.Add method using a Client ID. The end result I need, is to populate a Date Picker for an ASP:Textbox, with an onfocus event.

Example as follows:

//setting the value of the item from the dataset 
 string textCode = ds.Tables["CONTROLS"].Rows[1]["TEXTCODE"].ToString();

//inserting the value for use with ClientID
textCode.Attributes.Add("onfocus", "datepicker('" + textCode.ClientID + "');");

I am getting the error of: "'string' does not contain a definition for 'ClientID' accepting a first argument of 'string' could be found (are you missing a using directive or an assembly reference")".

When I attempt to convert or set another variable to an HtmlControl which ClientID is available for as such:

HtmlControl txtCode = textCode;

I get the following error: "Cannot implicitly convert 'string' to 'System.Web.UI.HtmlControls.HtmlControl'"

How do I convert to use this dynamic ID?

Thank you in advance for your suggestions.

1

There are 1 best solutions below

2
Ivan Yuriev On

More detailed answer after the comments.. I seems like you're storing the asp.net server control Id in your database, and after retrieving it from database you got textCode variable with the id of control on your page ("txtCNo").

So the first step is to find the control with this id on your page. The simple way is Page.FindControl(...) method, but you'd better look at this article for more advanced situations: Better way to find control in ASP.NET

I also noticed that you're trying to add onfocus event with call to some javascript function datepicker(''). There is a better way to send a client Id of the control that was found in first step. (For more info about server vs client IDs look at this article: https://msdn.microsoft.com/en-us/library/1d04y8ss.aspx)

So, your code should look something like:

//setting the value of the item from the dataset 
string controlId = ds.Tables["CONTROLS"].Rows[1]["TEXTCODE"].ToString();

var control = Page.FindControl(controlId);
if(control != null)
{
    control.Attributes.Add("onfocus", "datepicker('" + control.ClientID + "');");
}