【问题标题】:Asp.net - Changing Textbox field into label in gridview at code behindAsp.net - 在代码后面的网格视图中将文本框字段更改为标签
【发布时间】:2014-04-16 04:22:42
【问题描述】:
<ItemTemplate>
    <asp:TextBox ID="Q1" runat="server" Text='<%# Bind("Q1") %>'></asp:TextBox>
</ItemTemplate>
.
.
.
<ItemTemplate>
    <asp:TextBox ID="Q2" runat="server" Text='<%# Bind("Q2") %>'></asp:TextBox>
</ItemTemplate>

我目前有一个带有字段作为文本框的页面,我想根据后面代码中的条件更改其中一些标签。

例如如果 Window_name='Q2' --> 制作 Q2 Q3 Q4 文本框和 Q1 标签 如果是 Window_name='Q3' 则制作 Q3 和 Q4 文本框,但 Q1 和 Q2 标签

顺便说一句,我没有使用编辑/选择网格视图模式,因为我将它批量更新网格视图(一个按钮更新所有行)

【问题讨论】:

  • 您标记为 C# 和 vb.net。选择一个,否则人们会觉得有必要同时提供两种翻译的答案。
  • 你想让一个文本框看起来像标签,你想在哪个事件上做它?
  • Valamas:我在 C# 和 vb.net 中都感觉很舒服,通常很容易转换/理解另一个
  • 为什么要将TextBox改为Label?虽然您有办法这样做...例如使用 css 更改 TextBox 样式(例如 Label),或者创建两者并根据条件显示一个并隐藏另一个...
  • 我一直在尝试显示/隐藏但没有成功,我们将不胜感激

标签: c# asp.net gridview textbox


【解决方案1】:

我正在尝试帮助您提供两个控件的示例和示例网格视图 ID 'GridView1',请根据您的代码进行更改:

您可以创建标签而不是在代码隐藏中显示文本框,或者最初创建文本框和标签并在需要时显示它们。

除了在 Page_Load 函数中执行此操作,您还可以在 GridView 的“RowDataBound”事件中执行此操作,并在每次回发完成时绑定 GridView。

ASPX 代码:

<ItemTemplate>
      <asp:TextBox ID="Q1" runat="server" Text='<%# Bind("Q1") %>'></asp:TextBox>
      <asp:Label ID="Label1" runat="server" Text='<%# Bind("Q1") %>' Visible="false">
      </asp:Label>
</ItemTemplate>

.....

<ItemTemplate>
      <asp:TextBox ID="Q2" runat="server" Text='<%# Bind("Q2") %>'></asp:TextBox>
      <asp:Label ID="Label2" runat="server" Text='<%# Bind("Q2") %>' Visible="false">
      </asp:Label>
</ItemTemplate>

代码背后:

protected void Page_Load(object sender, EventArgs e)
        {
            //Bind your grid view
            GridView1.DataBind();
        }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                int rowIndex = e.Row.RowIndex;
               //First fetch your textboxes and labeles 
                TextBox textBoxQ1 = GridView1.Rows[rowIndex].FindControl("Q1") as TextBox;
                TextBox textBoxQ2 = GridView1.Rows[rowIndex].FindControl("Q2") as TextBox;

                Label Label1 = GridView1.Rows[rowIndex].FindControl("Label1") as Label;
                Label Label2 = GridView1.Rows[rowIndex].FindControl("Label2") as Label;

                if (Window_name.Equals("Q2"))
                {
                    //Set 'visiblity' to 'true' for those LABEL you want to show. Sample one below
                    Label2.Visible = false;
                    //Set 'visibilty' to 'false' for those TEXT BOXES you want to hide. Sample one below
                    textBoxQ2.Visible = false;
                }
            }

如有任何疑问,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多