关于GridView的开发应用
之前是用的Repeater控件,如果在此基础上添加修改功能稍显麻烦
于是换成了GridView控件.现 将其中使用比较特殊的功能列出来共享:
[1]合并列头-添加动态行
需要在数据绑定时进行-RowDataBound
protected void gvShowDatas_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells.Clear();
e.Row.Cells.Add(new TableCell());
e.Row.Cells[0].Text = "周 期";
e.Row.Cells.Add(new TableCell());
e.Row.Cells[1].Text = "黄金 涨跌";
e.Row.Cells[1].ColumnSpan = 2;
e.Row.Cells.Add(new TableCell());
e.Row.Cells[2].Text = "白银 涨跌";
e.Row.Cells[2].ColumnSpan = 2;
e.Row.Cells.Add(new TableCell());
e.Row.Cells[3].Text = "铂 涨跌";
e.Row.Cells[3].ColumnSpan = 2;
e.Row.Cells.Add(new TableCell());
e.Row.Cells[4].Text = "钯 涨跌";
e.Row.Cells[4].ColumnSpan = 2;
e.Row.Cells.Add(new TableCell()); //e.Row.Cells[5].Style.Add("text-align", "center");
e.Row.Cells[5].Text = "修 改";
e.Row.CssClass = "tb_title2";
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = dataTime;
e.Row.Cells[0].Attributes.Add("text-align", "center");
e.Row.Cells[0].ColumnSpan = 10;
for (int j = 1; j <= 9; j++)
{
e.Row.Cells[j].Visible = false;
}
}
}
代码中先进行列头的合并,并设置每个CELL的ColumnSpan属性.
在尾行处理时需要设置ShowFooter的属性为TRUE
通过手动的方式隐藏其它的单元格?[此处没有想明白-请高手指点...]
[2]由于在GridView控件的绑定隐藏列时,发送到客户端的数据中无隐藏域,特别是需要隐藏数据ID时[数据主键]无法获取.
还好GridView提供了DataKeyNames和DataKeys属性

//数据绑定
gvShowDatas.DataSource = dt;
gvShowDatas.DataBind();
gvShowDatas.DataKeyNames = new string[] { "ID"};
//获取主键值
string editID = gvShowDatas.DataKeys[gvShowDatas.EditIndex]["ID"].ToString();通过此种方式保存处理数据的主键
[3]
<ControlStyle Width="50px" />
<ItemStyle CssClass="tb_title2" />
</asp:BoundField>
ControlStyle的 Width值将设置该列处理编辑状态时TextBox的宽度
[4]在绑定数据时,有些数据需要格式化.还好GridView提供了格式化属性
<asp:BoundField DataField="WChange" ReadOnly="True" DataFormatString="{0:F}" HtmlEncode="false" HeaderText="周涨跌幅(%)">
<ItemStyle CssClass="tb_title2" />
</asp:BoundField>
[5]GridView中的模板列使的数据绑定与处理更加灵活.
<asp:TemplateField HeaderText="修改" ShowHeader="False">
<ItemTemplate>
<asp:HyperLink NavigateUrl='<%#"OperaterManage.aspx?salesID="+Eval("ID")%>' ID="salesID"
Text="修改" runat="server" Target="_self"></asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="tb_title2" />
</asp:TemplateField>[6]添加删除时的提示
protected void salesInfos_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[5].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('请确认执行删除:\"" + e.Row.Cells[0].Text + "\"!')");
}
}
}
出处:http://bober.cnblogs.com/
CARE健康网: http://www.aicareyou.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。


浙公网安备 33010602011771号