首页 新闻 赞助 找找看

asp.net如何在运行时,根据控件的属性名动态的添加控件的属性?

0
悬赏园豆:5 [待解决问题]

问题描述:要实现的功能很简单,就是根据checkboxlist中选择的值,设置label的一些属性。但是我想不用硬编码Label1.Font.Bold这种方式,而是根据item的value动态设置。代码如下:

foreach (ListItem item in CheckBoxList1.Items)

        {

            if (item.Selected==true)

            {

//item.Value的值为Bold。通过item.Value可以得知我是想设置Label1.Font的Bold 为 true。

                Label1.Font.Bold = true;//硬编码。这个当然可以

//但是我想通过item.Value获取的值动态的设置,而不是硬编码代码中。于是想用下面的方法:

                string ff =item.Value; //用ff代替bold,拼出Label1.Font.Bold 

                Label1.Font.ff = true;//这个为什么不行呀??有没有类似的解决方法??

            }

        }

 

试验过的其它方法:

    通过Table1.Attributes.Add("style", " text-align:center;")可以设置表中文字的对齐方式为居中。是在HTML中加了sytle属性。

    然后我就想通过此方法给label控件加上Font-Underline="True";写法为Label1.Attributes.Add("Font-Underline", "True");结果,属性还是加到html中了,有没有一个方法可以给web控件加属性呀!

shidaoke的主页 shidaoke | 初学一级 | 园豆:199
提问于:2012-04-08 17:22
< >
分享
所有回答(2)
0

label1.Font[""]

看看是不是有这样的东西,如果没有,就需要通过反射来做了。

chenping2008 | 园豆:9836 (大侠五级) | 2012-04-08 19:57

谢谢,没找到类似label1.Font[""]的方法,倒是有个Table1.Attributes[],和Table1.Attributes.Add()功能一样。正在看反射方面的资料。

支持(0) 反对(0) shidaoke | 园豆:199 (初学一级) | 2012-04-09 09:30

用反射弄出来了

支持(0) 反对(0) shidaoke | 园豆:199 (初学一级) | 2012-04-09 18:54
0

折腾了一天,终于弄出来了,用的反射。感觉如果有个类似label1.font["Bold"]就方便多了。
代码如下:
aspx代码:
 <asp:Label runat="server" Text="00000000"></asp:Label>   
  <asp:CheckBoxList runat="server"  
  RepeatDirection="Horizontal">
  <asp:ListItem>Bold</asp:ListItem>
  <asp:ListItem>Italic</asp:ListItem>
  <asp:ListItem>Strikeout</asp:ListItem>
  <asp:ListItem>Overline</asp:ListItem>
  </asp:CheckBoxList>   
  <asp:Button runat="server" Text="Button" onclick="Button1_Click" />  

cs代码:
 protected void Button1_Click(object sender, EventArgs e)
  {
    
  Type tyOfLbl = Label1.GetType();
  PropertyInfo[] lblProperties = tyOfLbl.GetProperties();
  foreach (PropertyInfo lblProperty in lblProperties)
  {
  //这里只是设置font的属性,如果要设置text的属性的话,再加上if (lblProperty.Name=="Text"){}
  if (lblProperty.Name=="Font")
  {
  Type lblfont = Label1.Font.GetType();
  PropertyInfo[] lblfontProperties = lblfont.GetProperties();
  foreach (PropertyInfo lblFontProperty in lblfontProperties)
  {   
  if (CheckBoxList1.Items.FindByValue(lblFontProperty.Name) != null)//这句一定要加上,否则出错,对象未引用。原因应该是对象是null,在下边的语句中没法操作。
  {
  //把CheckBoxList1和Label1联系起来的是 <asp:ListItem>Overline</asp:ListItem>中的 Overline等,即label控件font中的属性名字。
  //下面这句话的意思是:如果现在的属性在CheckBoxList1是选中的话,则设置相应的label属性;
  if (CheckBoxList1.Items.FindByValue(lblFontProperty.Name).Selected)
  {
  lblFontProperty.SetValue(Label1.Font, true, null);
  }
  else
  {
  lblFontProperty.SetValue(Label1.Font, false, null);
  }
    
  }
  }
  }
  }
  }

shidaoke | 园豆:199 (初学一级) | 2012-04-09 18:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册