0

我正在动态填充保存在我的数据库中的文本框的 ID。从确定搜索参数的数据集中提取值时,我将其设置为字符串。

我现在想将字符串参数用作使用客户端 ID 的 Attributes.Add 方法的动态 ID。我需要的最终结果是使用 onfocus 事件为 ASP:Textbox 填充日期选择器。

示例如下:

//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 + "');");

我收到以下错误:“'string' does not contain a definition for 'ClientID' accept the first argument of 'string' can be found(您是否缺少 using 指令或程序集引用”)”。

当我尝试将另一个变量转换或设置为 ClientID 可用的 HtmlControl 时:

HtmlControl txtCode = textCode;

我收到以下错误:“无法将 'string' 隐式转换为 'System.Web.UI.HtmlControls.HtmlControl'”

如何转换为使用此动态 ID?

预先感谢您的建议。

4

1 回答 1

0

评论后更详细的答案.. 我似乎将 asp.net 服务器控件 ID 存储在数据库中,从数据库中检索它后,您在页面上获得了带有控件 ID 的 textCode 变量(“txtCNo”)。

所以第一步是在你的页面上找到这个id的控件。简单的方法是 Page.FindControl(...) 方法,但你最好看看这篇文章以获得更高级的情况:Better way to find control in ASP.NET

我还注意到您正在尝试通过调用某些 javascript 函数 datepicker('') 添加 onfocus 事件。有一种更好的方法可以发送在第一步中找到的控件的客户端 ID。(有关服务器与客户端 ID 的更多信息,请参阅本文:https ://msdn.microsoft.com/en-us/library/1d04y8ss.aspx )

因此,您的代码应类似于:

//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 + "');");
}
于 2016-04-07T20:20:56.010 回答