C# 如何在运行时从codebehind更改CSS键的值?

C# 如何在运行时从codebehind更改CSS键的值?,c#,asp.net,css,C#,Asp.net,Css,我有一个相当简单的页面,它查询web服务以从SQL server提取数据,返回大小不同的通用列表。我试图做的是,在运行时调整div的高度,在foreach循环的每次迭代中向现有CSS键添加一定数量的像素,以便投影列表不会溢出容器div 我用于将列表放在页面上的代码如下: int total = 0; lstUsageServices.Text = string.Empty; lstUsageRequests.Text = string.Empty; if (txtAccount.Text !=

我有一个相当简单的页面,它查询web服务以从SQL server提取数据,返回大小不同的通用列表。我试图做的是,在运行时调整div的高度,在foreach循环的每次迭代中向现有CSS键添加一定数量的像素,以便投影列表不会溢出容器div

我用于将列表放在页面上的代码如下:

int total = 0;
lstUsageServices.Text = string.Empty;
lstUsageRequests.Text = string.Empty;
if (txtAccount.Text != string.Empty)
{
soapClient = new UsageService.ServiceSoapClient();
foreach (UsageClient.UsageService.Usage current in soapClient.GetUsage(txtAccount.Text, startPicker.SelectedDate, endPicker.SelectedDate))
{
lstUsageServices.Text += current.Service + "<br />";
lstUsageRequests.Text += current.Requests.ToString() + "<br />";
total += current.Requests;                        
}
lstUsageServices.Text += "<strong>Total</strong>";
lstUsageRequests.Text += "<strong>" + total.ToString() + "</strong>";
int-total=0;
lstUsageServices.Text=string.Empty;
lstUsageRequests.Text=string.Empty;
if(txtAccount.Text!=string.Empty)
{
soapClient=新的UsageService.ServiceSoapClient();
foreach(UsageClient.UsageService.Usage当前在soapClient.GetUsage(txtcount.Text、startPicker.SelectedDate、endPicker.SelectedDate)中)
{
lstUsageServices.Text+=current.Service+“
”; lstUsageRequests.Text+=current.Requests.ToString()+“
”; 总数+=当前的请求数; } lstUsageServices.Text+=“总计””; lstUsageRequests.Text++“”+total.ToString()+””;
我想做的是在foreach中添加一行以引用div:

<div class="main" runat="server" id="mainDiv">

并在每次迭代中增加CSS“height:Xpx;”

我希望有人能帮上忙,这似乎不是件难事!提前谢谢:)

一个简单的方法可以

mainDiv.Attributes.CssStyle.Add("height", "Xpx");

如果你想让
div
的高度随着内容的增加而增加,你就不能让它的高度保持自动吗?试着让它保持自动,似乎并不值得,即使我添加了一个!重要的是,这个想法是正确的;OP需要计算X,然后在循环后分配它。这很好,所以我只需要计算行数,然后将计数乘以一行占用的像素数。我会不断添加更多属性,这不是一个问题吗?最近的属性会简单地替换上一个吗?不幸的是,没有乐趣,添加了下面的内容,现在可以使用mainDiv.attributes.csssstyle.Add(“height”,(420+(rowCount*10)).ToString();最终使用了一个控件,如果设置为“自动”,该控件将强制调整div的高度。