您的位置:首页 > 运维架构

GridView 的更新删除、操作及例子详解(结合textbox 和dropdownlist)

2012-02-20 14:58 447 查看
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<%--如果有自定义的模板,不适用 自动生成字段 ,需 AutoGenerateColumns="False" --%>

<%-- GridView 控件以控件状态存储这些键字段值。如果这些值包含敏感信息,则强烈建议您通过将 ViewStateEncryptionMode
属性设置为 ViewStateEncryptionMode.Always 来启用视图状态加密。--%>

<asp:GridView ID="gvStudent" runat="server"  AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowcancelingedit="gvStudent_RowCancelingEdit"
onrowdatabound="gvStudent_RowDataBound" onrowdeleting="gvStudent_RowDeleting"
onrowediting="gvStudent_RowEditing" onrowupdating="gvStudent_RowUpdating"
onselectedindexchanging="gvStudent_SelectedIndexChanging"
onpageindexchanging="gvStudent_PageIndexChanging" DataKeyNames="id">
<RowStyle BackColor="#EFF3FB" />

<%--DataKeyNames 一个数组,包含了显示在gridview控件中的项的主键字段的名字。
指定表示数据源主键的字段,为了是gridview控件的自动更新和删除功能,必须设置datakeynames="主键"。
为了指定要更新或删除的行,这些键字段的值被传递到数据源控件。
当设置了datakeynames属性时,gridview控件用来自指定字段的值填充它的datakeys集合,提供了一种
访问每个行的主键的便捷方法。--%>

<%-- 在使用自动生成的字段列时(通过将 AutoGenerateColumns 属性设置为 true),GridView 控件确保与 DataKeyNames 属性中指定的字段相对应的列是只读的。--%>
<%--如果将某个列字段的 Visible 属性设置为 false,则在 GridView 控件中将不显示该列,该列中的数据也不会往返于客户端。如果希望某个不可见的列中的数据可以供客户端使用,则向 DataKeyNames 属性添加相应的字段名称。--%>
<%--标记中的 GridView 元素的 DataKeyNames 特性通过使用逗号分隔名称来指定两个键字段--%>
<Columns>
<asp:BoundField HeaderText="编号" Visible="false"  DataField="id"/>

<asp:TemplateField HeaderText ="姓名">
<ItemTemplate>
<%#Eval("name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:textbox ID ="TBName" Text='<%#Eval("name") %>' runat="server">'>
</asp:textbox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<%#Eval("sex").Equals(true) ? "男" : "女"%><%--性别是bit类型,显示应该为(男、女)--%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDLSex" runat="server" Width="90px"  AutoPostBack="false"/><%--AutoPostBack="false" 不回发--%>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="班级">
<ItemTemplate>
<%#Eval("class") %>
</ItemTemplate>
<EditItemTemplate>
<%--   <asp:HiddenField ID="HDFClass" runat="server" Value='<%# Eval("classID") %>' />--%><%--当dropdownlist 绑定数据源,需显示name,同事需对classID进行操作时,可以用hiddenField保存classID的值--%>
<asp:DropDownList ID="DDLClass" runat="server" Width="90px" /><%-- class 可更改,dropdownlist 供选择--%>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="成绩">
<ItemTemplate>
<%#Eval("grade")%>
</ItemTemplate>
<EditItemTemplate>
<asp:textbox ID ="TBGrade" Text='<%#Eval("grade") %>' runat="server">'> <%--若grade可更改,签入textbox--%>
</asp:textbox>
</EditItemTemplate>
</asp:TemplateField>
<%-- <asp:BoundField HeaderText="成绩" DataField="grade" ReadOnly="true" /> --%>  <%--若grade列不可改,只需这样写--%>
<asp:BoundField HeaderText ="建立时间"  DataField="createtime"  ReadOnly="true" />
<asp:CommandField ShowDeleteButton="true" ShowEditButton="true" HeaderText="操作" />

</Columns>
<PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
<RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>
</html>

C# 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)//首次加载和访问,ispostback=true 表示为相应客户端回发而加载
GridViewBind();
}
protected void gvStudent_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{

}
protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
//绑定班级
if (((DropDownList)e.Row.FindControl("DDLClass")) != null)
{
DropDownList ddlclass = (DropDownList)e.Row.FindControl("DDLClass");

//生成dropdownlist 的值,绑定数据
string sqlStr = "select distinct(class) from student";
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(StrConn);

conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
da.Fill(ds,"class");
conn.Close();

ArrayList alClass = new ArrayList();

for (int i = 0; i < ds.Tables["class"].Rows.Count; i++)
{
alClass.Add(ds.Tables["class"].Rows[i]["class"]);
}
ddlclass.DataSource = alClass;//从库中获取数据
ddlclass.DataBind();
}
//绑定性别
if (((DropDownList)e.Row.FindControl("DDLSex")) != null)
{
DropDownList ddlsex = (DropDownList)e.Row.FindControl("DDLSex");

ArrayList al = new ArrayList();
al.Add("女");  // 索引 0
al.Add("男"); //索引 1
ddlsex.DataSource = al;  //dropdownlist的另一数据源(自定义数据
ddlsex.DataBind();
}
}
protected void gvStudent_RowEditing(object sender, GridViewEditEventArgs e)
{
gvStudent.EditIndex = e.NewEditIndex;//所编辑行的索引
GridViewBind();
}
protected void gvStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvStudent.EditIndex = -1;
GridViewBind();
}
protected void gvStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
try
{

//以下三种方式获取 Id,前提是确保datakeynames="id"
// 2. string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();
// 1. string id = gvStudent.DataKeys[e.RowIndex].Value.ToString();
string id = ((GridView)sender).DataKeys[e.RowIndex].Values["id"].ToString();//DataKeys gridview控件中每一行的数据键值

string name = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBName")).Text;
int sex = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedIndex;//选定项的索引  0

//string sexs1 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedItem.ToString();//索引最小的选定项 男
//string sexs2 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedValue.ToString();//选定项的值 男
//string sex3 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).Text;//选定项的text 男

string className = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLClass")).SelectedValue;
string grade = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBGrade")).Text;
DateTime updatetime = DateTime.Now;

SqlConnection conn = new SqlConnection(StrConn);

conn.Open();

string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "',grade='"+grade+"'  where id=" + id; //grade可改时的sql
// string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "'  where id=" + id;// grade 不可改时的sql

SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
cmd.Dispose();
if (conn.State.ToString() == "open")
conn.Close();

gvStudent.EditIndex = -1;
GridViewBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}

}
protected void gvStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();

string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();
string sql = "delete from student where id="+id ;

try
{
SqlConnection conn = new SqlConnection(StrConn);
if (conn.State.ToString() == "Closed") conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);
comm.ExecuteNonQuery();
comm.Dispose();
if (conn.State.ToString() == "Open") conn.Close();

gvStudent.EditIndex = -1;
GridViewBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}

}

private void GridViewBind()
{
string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();    //在web.config中定义过了connectionString
// 或  string StrConn = "Data Source=LENOVO-THINK\\FMSQLSERVERR2;Initial Catalog=MyTest;Integrated Security=True";    //webconfig 中未定义,直接在C# 代码中写连接字符串
string sqlStr = "select * from student";
DataSet ds = new DataSet();
try
{
SqlConnection conn = new SqlConnection(StrConn);

conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
da.Fill(ds);
conn.Close();
DataTable tb = ds.Tables[0];

gvStudent.DataSource = tb;
gvStudent.DataBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:"+ex.Message);
Response.End();
}

}
protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvStudent.PageIndex = e.NewPageIndex;//当前显示页的索引
GridViewBind();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐