你的问题可以用数据绑定解决啊,看下面的例子,SqlConnection conn=new SqlConnection("server=localhost;database=northwind;uid=sa;password=111");
SqlCommand sqlCommand1=new SqlCommand("SELECT * FROM customers",conn);
conn.Open();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(sqlCommand1.CommandText,conn);
dt = new System.Data.DataSet();
da.Fill(dt,"customers");
DataView dv = new DataView(dt.Tables[0]);
this.textBox6.DataBindings.Add("Text",dv,"customerid");
DataGrid1.SetDataBinding(dv,"");
BindingManagerBase myBind ;
增加语句
this.BindingContext[dv,""].AddNew;
删除语句
this.BindingContext[dv,""].RemoveAt(this.BindingContext[dv,""].Position)
向前
this.BindingContext[dv,""].Position ++;
向后
this.BindingContext[dv,""].Position --;
基本上已经包括了数据库最常用的操作,
当所有的完成后调 用如下的语句更新回数据库
this.BindingContext[dv,""].EndCurrentEdit();
sqlDa.Update(dt.GetChanges());
dt.AcceptChanges();
SqlCommand sqlCommand1=new SqlCommand("SELECT * FROM customers",conn);
conn.Open();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(sqlCommand1.CommandText,conn);
dt = new System.Data.DataSet();
da.Fill(dt,"customers");
DataView dv = new DataView(dt.Tables[0]);
this.textBox6.DataBindings.Add("Text",dv,"customerid");
DataGrid1.SetDataBinding(dv,"");
BindingManagerBase myBind ;
增加语句
this.BindingContext[dv,""].AddNew;
删除语句
this.BindingContext[dv,""].RemoveAt(this.BindingContext[dv,""].Position)
向前
this.BindingContext[dv,""].Position ++;
向后
this.BindingContext[dv,""].Position --;
基本上已经包括了数据库最常用的操作,
当所有的完成后调 用如下的语句更新回数据库
this.BindingContext[dv,""].EndCurrentEdit();
sqlDa.Update(dt.GetChanges());
dt.AcceptChanges();
我想利用datagrid中的编辑删除列来处理一些事情,他可以产生很多事件,比如DataGrid1_EditCommand,DataGrid1_CancelCommand,DataGrid1_UpdateCommand,DataGrid1_DeleteCommand等
if (e.Item.ItemIndex >= 0)
{
((LinkButton)e.Item.FindControl("lnkbtnDelete")).Attributes["onclick"]="javascript:return confirm('"确定要删除这个信息吗?"');";
}
在itembound()
LinkButton mybuton=new LinkButton();
mybuton=(LinkButton)e.item.cell[i].control[0];
mybuton.Attributes["onclick"]="javascript:retrun confirm('确定删除此信息?,"+DataBiner.Eval(container,DataItem."id").ToString())';";
1、调整TextBox的宽度
默认情况下,DataGrid编辑模式下的TextBox都因为宽度不合适而打乱整个DataGrid的布局,然而,可以通过在OnItemDataBound事件中加入调整代码:
private void DataGrid1_ItemDataBound(object source, DataGridItemEventArgs e)
{
if(e.Item.ItemIndex >= 0)
{
TextBox tb1 = (TextBox)e.Item.Cells[0].Controls[0];
tb1.Width = Unit.Pixel(85);
...
}
}
通过调整大小,使DataGrid在编辑模式下也显得整齐划一。2、增加DropDownList
为了添加一个自定义的编辑控件,取代系统默认的TextBox框,例如DropDownList,需要用到模板列TemplateColumn:
<asp:DataGrid ID="DataGrid1" runat=server ...>
<columns>
<asp:TemplateColumn HeaderText="columnA">
<ItemTemplate><asp:Label id="ssLabel" runat=server></asp:Label>
</ItemTemplate>
<EditTemplate><asp:DropDownList id="ssList" runat=server></asp:DropDownList>
</EditTemplate>
</asp:TemplateColumn>
...
</columns>
</asp:DataGrid>
其中,<ItemTemplate>为在非编辑模式下绑定数据的方式,<EditTemplate>为在编辑模式下绑定数据的方式。然后需要在OnItemDataBound事件中添加以下数据绑定代码:
private void DataGrid1_ItemDataBound(object source, DataGridItemEventArgs e)
{
if (e.Item.ItemIndex >= 0) {
DataRowView row = dt.DefaultView[e.Item.ItemIndex]; //supose that DataGrid1.DataSource = dt.DefaultView; if (e.Item.ItemIndex == DataGrid1.EditIndex) { //edit mode
DropDownList list = (DropDownList)e.Item.Cells[0].Controls[1];
//bind data to dropdownlist control
//you can do this also at design time
for(int i=0; i<10; i++) {
list.Items.Add("Item" + i.ToString());
//supose that the column list lies is first column of datatable
if (row[0].ToString().Equals("Item" + i.ToString() )
list.SelectedIndex = i;
}
}
else { //normal mode
Label label = (Label)e.Item.Cells[0].Controls[1];
label.Text = row[0].ToString();
}
}
}
这样当DataGrid的一行为编辑模式下时,该列就出现DropDownList,并且选定的内容为当前单元的值。
.aspx文件:
<asp:datagrid id="dgrConfirm" tabIndex="3" runat="server" AutoGenerateColumns="False" CellPadding="0"
BorderWidth="0px" BorderStyle="None" OnDeleteCommand="OnDelete" OnCancelCommand="OnCancel"
OnEditCommand="OnEdit" OnUpdateCommand="OnUpdate" AllowPaging="True" OnPageIndexChanged="PageIndexChanged"
OnItemDataBound="OnItemDataBound" CellSpacing="1" Width="100%" Height="100%">
<ItemStyle CssClass="login-td03"></ItemStyle>
<HeaderStyle Font-Bold="True" CssClass="login-title01"></HeaderStyle>
<FooterStyle Font-Bold="True" CssClass="login-title01"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="yhm" ReadOnly="True" HeaderText="用户名">
<ItemStyle Width="120px"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="zsxm" ReadOnly="True" HeaderText="真实姓名">
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="xb" ReadOnly="True" HeaderText="性别"></asp:BoundColumn>
<asp:BoundColumn DataField="dzyj" ReadOnly="True" HeaderText="电子邮件"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="状态">
<ItemTemplate>
<%# DataBinder.Eval(Container,"DataItem.zt")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtState" Runat =server Width="30" Text='<%# DataBinder.Eval(Container,"DataItem.zt")%>' cssclass="login-input03">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="cmdEdit" Runat="server" CommandName="Edit" text="修改" CssClass="login-link01"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="cmdCancel" Runat="server" CommandName="Cancel" text="取消" CssClass="login-link01"></asp:LinkButton>
<asp:LinkButton id="cmdUpdate" Runat="server" CommandName="Update" text="更新" CssClass="login-link01"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:LinkButton id="cmdDel" Runat="server" text="删除" CommandName="Delete" CssClass="login-link01"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>.cs文件:
//修改数据
protected void OnEdit(object send ,DataGridCommandEventArgs e)
{
DataSet ds =new DataSet();
ds=this.ReadTeacher();
this.dgrConfirm.EditItemIndex=Convert.ToInt32(e.Item.ItemIndex );
this.dgrConfirm.DataSource=ds;
this.dgrConfirm.DataBind();
}
//更新数据
protected void OnUpdate(object send ,DataGridCommandEventArgs e)
{
SqlConnection sqlConn=new SqlConnection(strConn);
sqlConn.Open();
DataSet ds =new DataSet();
ds=this.ReadTeacher();
int row=Convert.ToInt32 (this.dgrConfirm.CurrentPageIndex)*10+Convert.ToInt32(e.Item.ItemIndex );
TextBox EditText=null;
EditText=(TextBox)e.Item.FindControl("txtState");
string strUserName=ds.Tables[0].Rows[row]["yhm"].ToString();
string strUpdate="Update jcjsqd set zt="+Convert.ToInt32(EditText.Text)+" where yhm='"+strUserName+"'";
SqlCommand sqlComm=new SqlCommand(strUpdate,sqlConn);
sqlComm.ExecuteNonQuery();
sqlConn.Close();
ds=this.ReadTeacher();
this.dgrConfirm.EditItemIndex=-1;
this.dgrConfirm.DataSource=ds;
this.dgrConfirm.DataBind();
}
//取消操作
protected void OnCancel (object send ,DataGridCommandEventArgs e)
{
this.dgrConfirm.EditItemIndex=-1;
DataSet ds =new DataSet();
ds=this.ReadTeacher();
this.dgrConfirm.DataSource=ds;
this.dgrConfirm.DataBind();
}
//删除记录
protected void OnDelete(object send ,DataGridCommandEventArgs e)
{
db=new UserDB();
SqlConnection sqlConn=new SqlConnection(strConn);
sqlConn.Open();
DataSet ds =new DataSet();
ds=this.ReadTeacher();
int row =Convert.ToInt32 (this.dgrConfirm.CurrentPageIndex)*10+Convert.ToInt32(e.Item.ItemIndex );
int nTeacherID=db.ReadTeacherID(ds.Tables[0].Rows[row]["yhm"].ToString ());
string strUserName=ds.Tables[0].Rows [row]["zsxm"].ToString ();
int nUserRoles=db.GetRoles( strUserName);
if (nUserRoles==4)
{
SqlCommand sqlCommand = new SqlCommand("msp_scjs", sqlConn);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@teacherid", SqlDbType.Int,4);
sqlCommand.Parameters["@teacherid"].Value = nTeacherID;
sqlCommand.ExecuteNonQuery();
ds=this.ReadTeacher();
this.dgrConfirm.DataSource=ds;
this.dgrConfirm.DataBind ();
sqlConn.Close ();
}
}
//提示确定删除对话框
protected void OnItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType ==ListItemType.Item || e.Item.ItemType ==ListItemType.AlternatingItem )
{
e.Item.Attributes.Add("onmouseover","this.style.backgroundcolor='66FF33'");
e.Item.Attributes.Add("onmouseout","this.style.backgroundcolor='F9F9F9'");
DataSet ds =new DataSet();
LbDelete=(LinkButton)(e.Item.FindControl ("cmdDel"));
int row =Convert.ToInt32 (this.dgrConfirm.CurrentPageIndex)*10+Convert.ToInt32(e.Item.ItemIndex );
SqlConnection sqlConn=new SqlConnection(strConn);
string strSQL="select zsxm from jcjsqd ";
SqlDataAdapter sqlAdapter =new SqlDataAdapter(strSQL,sqlConn);
sqlAdapter.Fill(ds);
string strUserName=ds.Tables[0].Rows[row]["zsxm"].ToString();
db=new UserDB();
int nUserRoles=db.GetRoles( strUserName);
if (nUserRoles==2)
{
LbDelete.Attributes.Add("onclick", "return alert('该用户是课程管理员不可以删除!');");
}
else if (nUserRoles==3)
{
LbDelete.Attributes.Add("onclick", "return alert('该用户是章管理员不可以删除?');");
}
else if (nUserRoles==4)
{
LbDelete.Attributes.Add("onclick", "return confirm('你确定要删除该条记录吗?');");
}
}
}
{
((LinkButton)e.Item.FindControl("lnkbtnDelete")).Attributes["onclick"]="javascript:return confirm('"确定要删除吗?"');";
}
2。在删除按钮列中页眉设置为删除。然后在客户端页面<head>中加入下面代码即可
<script language="javascript">
function delete_confirm(e)
{
if (event.srcElement.outerText=="删除")
event.returnValue=confirm("确认是否删除!");
}
document.onclick=delete_confirm;
</script>