我遇到了麻烦!
我正在通过动态生成很多网格视图,其中列值为dinamic值。 列是一样的。
我想知道如何设置此列的大小。
这是我的代码,我的努力。
private void generateControls( List<List<DataRow>> grids)
{
DataTable dt = new DataTable();
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.Width = new Unit("100%");
//grv.RowStyle.Wrap = false;
grv.RowStyle.Width = new Unit("100%");
grv.ID = "grid_view" + i;
grv.DataSource = dt;
grv.DataBind();
/* grv.Columns[0].ItemStyle.Width = new Unit("5%");
grv.Columns[1].ItemStyle.Width = new Unit("7%");
grv.Columns[2].ItemStyle.Width = new Unit("12%");
grv.Columns[3].ItemStyle.Width = new Unit("12%");
grv.Columns[4].ItemStyle.Width = new Unit("7%");
grv.Columns[5].ItemStyle.Width = new Unit("7%");
grv.Columns[6].ItemStyle.Width = new Unit("23%");
grv.Columns[7].ItemStyle.Width = new Unit("22%");
grv.Columns[8].ItemStyle.Width = new Unit("5%");*/
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br />";
Panel panelGrid = new Panel();
panelGrid.ID = "panel_grid" + i;
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["Ocorrência"].ToString();
/*
* Capitalized
* TextInfo myTI = new CultureInfo("pt-BR", false).TextInfo;
string novoTipoOcorrencia = myTI.ToTitleCase(tipoOcorrencia);*/
int quantidade = lst.Count;
lblTipo.Text = " - " + tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button" + i;
lkBtn.Text = "Exibir | Ocultar";
lkBtn.Attributes["onClick"] = "javascript:return ocultaGrid('" + panelGrid.ID + "'), false";
panel_status.Controls.Add(lblBlankLines);
panel_status.Controls.Add(lkBtn);
panel_status.Controls.Add(lblTipo);
panelGrid.Controls.Add(grv);
panel_status.Controls.Add(panelGrid);
panel_status.DataBind();
i++;
}
}
我试图获取列,但是我收到错误,告诉我索引访问无效。 如何在该gridview中访问我的列?
答案 0 :(得分:5)
使用RowDataBound EventHandler:
计算索引并确保您不会尝试访问不存在的列。
请参阅链接以获取示例:
http://msdn.microsoft.com/en-us/library/ms178296(v=vs.100).ASPX
grv.RowDataBound + = grv_RowDataBound;
private void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = new Unit("5%");
e.Row.Cells[1].Width = new Unit("7%");
e.Row.Cells[2].Width = new Unit("12%");
e.Row.Cells[3].Width = new Unit("12%");
e.Row.Cells[4].Width = new Unit("7%");
e.Row.Cells[5].Width = new Unit("7%");
e.Row.Cells[6].Width = new Unit("23%");
e.Row.Cells[7].Width = new Unit("22%");
e.Row.Cells[8].Width = new Unit("5%");
}
}