日期:2014-05-18  浏览次数:20466 次

动态绑定datagrid列
在datagrid中动态修改某列的值,也就是查询字段更新那某值及绑定列值
当条件字段为业务人员时:
业务人员     数量
    d                 10
    s                 20
    a                 2

当条件字段为种类时:
海量         数量
    r             3
    q             20
    u             9



------解决方案--------------------
<asp:GridView ID= "GridView1 " runat= "server " AutoGenerateColumns= "False " DataSourceID= "SqlDataSource1 "
Width= "579px " AllowSorting= "True " OnRowDataBound= "GridView1_RowDataBound " OnRowEditing= "GridView1_RowEditing " PageSize= "3 ">
<Columns>
<asp:BoundField DataField= "abcid " HeaderText= "abcid " SortExpression= "abcid " />
<asp:BoundField DataField= "abcdq " HeaderText= "abcdq " SortExpression= "abcdq " />
<asp:BoundField DataField= "abcbm " HeaderText= "abcbm " SortExpression= "abcbm,abcdq " />
<asp:BoundField DataField= "abctime " HeaderText= "abctime " SortExpression= "abctime " />
<asp:CommandField ShowEditButton= "True " />
</Columns>
<RowStyle HorizontalAlign= "Center " />
</asp:GridView>

</div>
<asp:SqlDataSource ID= "SqlDataSource1 " runat= "server " ConnectionString= " <%$ ConnectionStrings:testConnectionString %> "
SelectCommand= "SELECT * FROM [abc] where abcid=@id ">
<SelectParameters>
<asp:ControlParameter ControlID= "TextBox1 " Name= "id " PropertyName= "Text " />
</SelectParameters>
</asp:SqlDataSource>

------解决方案--------------------
DataGrid/DataList在ASP.NET非常重要,凡显示Table类型的数据,大多会使用这两个控件。

一、方法

1、DataBind

很简单、最常用的方法。绑定数据用。需要注意的只有一点:执行了这个方法后,DataGrid(由于DataGrid和DataList极为相似,所以下面的介绍虽然是针对DataGrid,但与DataList也相差不远)里面所有的显示绑定数据的控件,都会显示DataSource里的数据,其余控件也将初始化成.aspx里设计的状态。

二、属性

1、DataSource

有DataBind的地方,就应该有DataSource。如果没有指定DataSource而执行DataBind,那DataGrid将什么也不会显示。

DataSource一般是DataSet、DataTable或者DataView。当然也可以绑定DataReader或者其他实现IEnumerable的类。

2、DataKeyField,DataKeys

当你在DataGrid中定位一行之后,肯定想知道这行在数据表里的位置,至少有五种方法可以做到这一点,设置DataGrid的DataKeyField就是这几种方法之一。

DataKeyField一般设置为数据表的Unique字段(否则就没意义了),通过DataKey可以得到这一行对应的关键字段的值。

DataKeys是DataKey的集合,通过行的索引来读取相应行的DataKey。

3、EditItemIndex,SelectedIndex,CurrentPageIndex,SelectedItem

这些属性都很好理解,看名字就知道是什么意思,需要注意的是,设置了EditItemIndex或者CurrentPageIndex后需要重新执行DataBind方法(当然,前面提到过,还需要设置DataSource)。

4、Columns

没什么好解释的,Columns就是Columns,列的集合,可以设置列的属性,包括Visible、HeaderText、FooterText、SortExpression等。

严重注意:自动生成的列,是不包含在Columns中的。只有在.aspx中显示声明的列和在代码中添加的列才会被包含在其中。

5、Items

俗话说,最后的都是最重要的,把Items作为最后一个属性来介绍,正式基于这样的理由。

Items是DataGridItem的集合,可以遍历当前DataGrid中显示数据的DataGridIte