您的位置:首页 > 其它

GridView中控件列使用方法小结

2009-07-15 09:06 489 查看
方法一.使用GridView自带ButtonField控件。典型代码如下:

<%@ Page language="C#" %>

<script runat="server">

void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{

// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{

// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);

// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
TableCell contactName = selectedRow.Cells[1];
string contact = contactName.Text;

// Display the selected author.
Message.Text = "You selected " + contact + ".";

}

}

</script>

<html>
<body>
<form runat="server">

<h3>ButtonField Example</h3>

<asp:label id="Message"
forecolor="Red"
runat="server"/>

<!-- Populate the Columns collection declaratively. -->
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">

<columns>

<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
<asp:boundfield datafield="CompanyName"
headertext="Company Name"/>
<asp:boundfield datafield="ContactName"
headertext="Contact Name"/>

</columns>

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. -->
<asp:sqldatasource id="CustomersSqlDataSource"
selectcommand="Select [CustomerID], [CompanyName], [ContactName], [ContactTitle] From [Customers]"
connectionstring="<%$ ConnectionStrings:NorthWindConnection%>"
runat="server">
</asp:sqldatasource>

</form>
</body>
</html>

以上代码来源于Msdnhttp://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.buttonfield(VS.80).aspx,原来自己以为ButtonField没有办法取到行号,可是在以上这个示例中显示,ButtonField已经自带了这个属性,只要在RowCommand事件中,转换一下e.CommandArgument即可。

方法二.运用模版列。该方法比较灵活。可以自指定CommandArgument绑定数据源上某一字段。典型代码如下:

CommandArgument='<%# Eval("Id") %>'

另:无论是方法一还是方法二,只要有办法取出GridView中事件源所在行号,那么也可以结合设置GridView的DataKeyNames属性,来获取数据源相关关键字,进行事件操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: