下面程序是与数据库相连接的,通过点击编辑按钮来直接改变数据库里的每一行,但是有些地方不明白,如e.item.Cells[1]
这个1,2 可不可以随便写,我把最后一个写成了e.item.Cells[5]就提示出错
数据库里定义了usernme,userpwd,chinese,math,english,total,grades
表名是:grade
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" debug="true" %>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<script language="c#" runat="server">
SqlConnection cnn;
public void Page_Load(Object src,EventArgs e)
{
cnn=new SqlConnection("Server=localhost;database=grade;user id=sa;password=123456");
cnn.Open();
if(!Page.IsPostBack)
{
databind();
}
}
ICollection CreatTable()
{
string strsel="Select*From grade";
SqlDataAdapter myadapter=new SqlDataAdapter(strsel,cnn);
DataSet ds=new DataSet();
myadapter.Fill(ds,"grade");
return ds.Tables["grade"].DefaultView;
}
void databind()
{
datagrid1.DataSource=CreatTable();
datagrid1.DataBind();
}
public void datagrid_editcommand(Object sender,DataGridCommandEventArgs e)
{
datagrid1.EditItemIndex=(int)e.Item.ItemIndex;
databind();
}
public void datagrid_cancelcommand(Object sender,DataGridCommandEventArgs e)
{
datagrid1.EditItemIndex=-1;
databind();
}
public void update_command(Object sender,DataGridCommandEventArgs e)
{
string intname=e.Item.Cells[1].Text;
int intchinese=(((TextBox)e.Item.Cells[2].Controls[0]).Text);
int intmath=(((TextBox)e.Item.Cells[3].Controls[0]).Text);
int intenglish=(((TextBox)e.Item.Cells[4].Controls[0]).Text);
int sel="Update grade Set chinese='"+intchinese+"',math='"+intmath+"',english='"+intenglish+"' Where usernme='"+intname+"'";
SqlCommand sqlcmd=new SqlCommand(sel,cnn);
sqlcmd.ExecuteNonQuery();
datagrid1.EditItemIndex=-1;
databind();
}
</script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>
<body>
<form runat="server">
<asp:DataGrid ID="datagrid1" runat="server"
AutoGenerateColumns="false"
HeaderStyle-BackColor="#9999FF"
AlternatingItemStyle-BackColor="#99CCFF"
OnEditCommand="datagrid_editcommand"
OnCancelCommand="datagrid_cancelcommand"
OnUpdateCommand="update_command"
MaitainState="false">
<columns>
<asp:EditCommandColumn HeaderText="操作区"
EditText="编辑"
UpdateText="更新"
CancelText="取消"
ButtonType="pushbutton"/>
<asp:BoundColumn HeaderText="姓名" DataField="usernme" ReadOnly="true"/>
<asp:BoundColumn HeaderText="语文" DataField="chinese"/>
<asp:BoundColumn HeaderText="数学" DataField="math"/>
<asp:BoundColumn HeaderText="英语" DataField="english"/>
</columns>
</asp:DataGrid>
</form>
</body>
</html>