要实现在GridView模板列中选择行的功能,可以采用以下步骤:
1.在GridView中添加模板列,并在模板列中添加一个复选框控件
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
2.在GridView的RowDataBound事件中为模板列中的复选框控件添加相关事件处理程序
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");
chk.Attributes["onclick"] = string.Format("toggleRowSelection(this,'{0}');", GridView1.ClientID);
}
}
3.在页面中添加JavaScript脚本,定义toggleRowSelection函数来实现行的选择功能
<script type="text/javascript">
function toggleRowSelection(chk, gridId) {
var row = chk.parentNode.parentNode;
if (chk.checked) {
row.style.backgroundColor = '#FFFFC6';
} else {
row.style.backgroundColor = '';
}
}
</script>
其中,toggleRowSelection函数可以再根据需求进行修改和完善,也可以利用第三方框架或插件来实现更加丰富的功能。
示例1:
GridView的数据源为DataTable时,可以实现点击模板列中复选框控件时,同时选中或取消选中所属行的所有单元格,并在服务器端获取选中行的相关数据。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Age");
for (int i = 1; i <= 5; i++)
{
DataRow row = dt.NewRow();
row["ID"] = i;
row["Name"] = "Name" + i;
row["Age"] = i * 10;
dt.Rows.Add(row);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");
chk.Attributes["onclick"] = string.Format("toggleRowSelection(this,'{0}');", GridView1.ClientID);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
List<string> selectedIDs = new List<string>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
if (chk.Checked)
{
string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
selectedIDs.Add(id);
}
}
}
//TODO:根据选中的ID处理相关业务逻辑
}
示例2:
通过Ajax异步请求方式在GridView中选择行,并实现选中行数的实时显示。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound2" GridLines="None">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div>
<input type="button" value="Submit" onclick="submitForm();" />
<span id="selectedCount" style="color:red;"></span>
</div>
<script type="text/javascript">
function toggleRowSelection(chk, gridId) {
var row = chk.parentNode.parentNode;
if (chk.checked) {
row.style.backgroundColor = '#FFFFC6';
row.setAttribute('isSelected', 'true');
} else {
row.style.backgroundColor = '';
row.removeAttribute('isSelected');
}
updateSelectedCount(gridId);
}
function updateSelectedCount(gridId) {
var selectedCount = 0;
var grid = document.getElementById(gridId);
if (grid) {
for (var i = 1; i < grid.rows.length; i++) {
var row = grid.rows[i];
if (row.getAttribute('isSelected') == 'true') {
selectedCount++;
}
}
document.getElementById('selectedCount').innerHTML = 'You have selected ' + selectedCount + ' row(s).';
}
}
function submitForm() {
var data = [];
var grid = document.getElementById('<%=GridView1.ClientID%>');
if (grid) {
for (var i = 1; i < grid.rows.length; i++) {
var row = grid.rows[i];
if (row.getAttribute('isSelected') == 'true') {
var id = row.cells[0].innerHTML;
var name = row.cells[1].innerHTML;
var age = row.cells[2].innerHTML;
data.push({ ID: id, Name: name, Age: age });
}
}
}
if (data.length > 0) {
var param = JSON.stringify({ dataList: data });
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'Default.aspx/ProcessData',
data: param,
dataType: 'json',
success: function (response) {
alert(response.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
} else {
alert('Please select some rows first.');
}
}
</script>
[WebMethod]
public static string ProcessData(List<GridViewDataItem> dataList)
{
string result = string.Empty;
if (dataList != null && dataList.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (GridViewDataItem item in dataList)
{
sb.AppendFormat("ID={0},Name={1},Age={2}", item.ID, item.Name, item.Age);
sb.AppendLine();
}
result = sb.ToString().Trim();
}
return result;
}
protected void GridView1_RowDataBound2(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = (CheckBox)e.Row.FindControl("CheckBox1");
chk.Attributes["onclick"] = string.Format("toggleRowSelection(this,'{0}');", GridView1.ClientID);
}
}
public class GridViewDataItem
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
其中,使用了jQuery库来实现Ajax异步请求,并通过WebMethod来处理服务器端返回的数据。在页面中添加了一个Submit按钮和一个显示选中行数的span元素。选中行数功能的实现通过updateSelectedCount函数来实现,具体实现方式是遍历GridView每一行的Dom元素,查找带有isSelected属性的行,并根据这些行的数量来更新选中行数的显示。最终的提交操作则通过submitForm函数来实现,这个函数首先将选中的行数据组装成JSON格式的参数,然后发起Ajax异步请求来向服务器端提交数据,处理结果将通过alert方式来显示给用户。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:asp.net GridView模板列中实现选择行功能 - Python技术站