首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有没有办法在后面的代码中使用变量来引用asp ID?

有没有办法在后面的代码中使用变量来引用asp ID?
EN

Stack Overflow用户
提问于 2019-03-25 04:49:11
回答 2查看 262关注 0票数 2

我正在尝试使用c#变量来删除属性。

在实际编写应用程序之前,我正在测试我的方法。

我尝试过javascript和jQuery,但没有找到任何可以用TextBox中的字符串值替换codebehind中的字符串值的方法。

代码语言:javascript
复制
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>

    </div>
    </form>

</body>

</html>
代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class index : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string straspID = "myText";


            bool fieldRequired = false;

            if (fieldRequired == false)
            {

                //FindControl("myText");
                FindControl(straspID);
                if (straspID != null)
           //         
                myText.Attributes.Remove("required");
          // I want to use straspID instead of the ID of the asp page
          // which will returned from a table - I'm simulating here
          // I get an error if I use straspID for remove attribute 
            }


        }

    }
}

我的预期结果是删除选定ID的属性。我当前收到一个语法错误。

EN

回答 2

Stack Overflow用户

发布于 2019-03-25 09:00:03

这个

代码语言:javascript
复制
            FindControl(straspID);

并不是像你想的那样。

你能检查一下你的index.aspx.designer.cs文件,看看是否有一个叫做'myText‘的受保护的成员变量吗?

如果有,你可以简单地这样做:

代码语言:javascript
复制
        if (fieldRequired == false)
        {
            myText.Attributes.Remove("required");
        }

如果没有名为myText的受保护成员,请在类级别添加一个到'index':-

代码语言:javascript
复制
namespace WebApplication2
{
    public partial class index : System.Web.UI.Page 
    {
        protected Textbox myText;

        (etc)

只要声明它的类型正确,并且具有相同的名称和大小写,就不需要求助于FindControl来访问服务器控件。

票数 0
EN

Stack Overflow用户

发布于 2019-04-02 09:13:02

private void loadform(List providerList) { foreach (ProviderInRequest请求in providerList) { // taget div for plan Control ctrl = FindControl("div“+ req.aspName);//如果我们找到了,则将visible设置为true。if (ctrl != null) {//将div设置为visible ctrl.Visible = true;

代码语言:javascript
复制
                // set label to proper text
                Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
                lbl.Text = displayName;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55328432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档