c# - 如何在 aspx.cs 页面中添加 css 类意味着页面后面的代码

标签 c# asp.net css

在 aspx 页面中,我使用以下内容:

<asp:GridView ID="grdCreateCustRepoUsers">
  <asp:TemplateField>
    <ItemTemplate>
      <div class="cst_checkbox_container1" id="cs1" runat="server">
        <div class="cst_checkbox unselected">
          <label class="checkbox_value">
          <asp:CheckBox ID="chkRead" runat="server" AutoPostBack="true" OnCheckedChanged="chkRead_CheckChanged" /></label>
        </div>
      </div>
    </ItemTemplate>
   </asp:TemplateField>
 </asp:GridView>

在我后面的代码中使用:

 cs1.Attributes.Add("class", "some-class");

但是它给出了 cs1 在当前上下文中不存在的错误。

我该如何解决?

最佳答案

cs1不会直接对页面可用,因为它将对 DataSource 中的每个元素重复为你的grdCreateCustRepoUsers GridView .

您需要做的是将其设置为 RowDataBound 的一部分GridView 事件.

使用 example from MSDN在 C# 中

void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
  if(e.Row.RowType == DataControlRowType.DataRow)
  {
     HtmlGenericControl div = (HtmlGenericControl)e.FindControl("cst_checkbox_container1");
     div.Attributes["class"] = "some_class";
  }
}

这是在 VB.NET 中的(我最初写的,因为我没有注意到标题中有 aspx.cs)

Sub grdCreateCustRepoUsers_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles grdCreateCustRepoUsers.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    Dim div as HtmlGenericControl = e.FindControl("cst_checkbox_container1")
    div.Attributes("class") = "some-class"
  End If
End Sub

(请注意,我对 GridView 控件的经验非常有限,但这是基于我对类似 <asp:Repeater> 控件的经验。因此,以上代码未经测试,但希望能为您指明正确的方向。)

关于c# - 如何在 aspx.cs 页面中添加 css 类意味着页面后面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15023756/

相关文章:

c# - 在 headless (headless)模式下独立运行 Unity,同时捕获屏幕截图

c# - 如何在当前组合框中选择一个值时使另一个组合框可见?

c# - 带有 xml、xsl 和 css 的 asp.net 简单报告框架

C# 检索屏幕更新矩形

javascript - 在不知道宽度的情况下将元素置于其上的居中

带有客户端拼写检查功能的 asp.net?

asp.net - WebActivator - 访问服务器对象/当前目录

c# - 我可以通过 ASP.NET 将对象从客户端 javascript 发送到服务器端代码吗?

html - CSS 导航栏在页面中间居中

javascript - 平滑滚动插件不允许我向下滚动页面