1。用列摸板做
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
SqlCommand cmd=new SqlCommand("delete from login where BH=@BH",cn);
cn.Open();
// SqlParameter sp=cmd.Parameters.Add("@BH",SqlDbType.VarChar,50);
// sp.Value=DataGrid1.DataKeys[e.Item.ItemIndex];
cmd.Parameters.Add("@BH",SqlDbType.VarChar,50);
cmd.Parameters["@BH"].Value=DataGrid1.DataKeys[e.Item.ItemIndex]; cmd.ExecuteNonQuery();
cn.Close();
bind();//数据重新绑定
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
SqlCommand cmd=new SqlCommand("delete from login where BH=@BH",cn);
cn.Open();
// SqlParameter sp=cmd.Parameters.Add("@BH",SqlDbType.VarChar,50);
// sp.Value=DataGrid1.DataKeys[e.Item.ItemIndex];
cmd.Parameters.Add("@BH",SqlDbType.VarChar,50);
cmd.Parameters["@BH"].Value=DataGrid1.DataKeys[e.Item.ItemIndex]; cmd.ExecuteNonQuery();
cn.Close();
bind();//数据重新绑定
我的后台编码是这个:能不能针对我的情况,具体帮我写一下?
先谢了~using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public class MyAdmin:Page
{
public DataGrid MyDataGrid;
void Page_load(object sender, EventArgs e)
{
string strConnection = "server=CHEYO;";
strConnection += "database=bookstore;uid=sa;password=vv7g51;";
string strSQL="select uid,id 用户名,passwd 密码,name,email,phone,idcard,address from customer order by uid asc;";
SqlConnection objConnection = new SqlConnection(strConnection);
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,strConnection);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
MyDataGrid.DataSource = objDataView;
MyDataGrid.DataBind();
}
}
private void DataGrid1_DeleteCommand(object source, system.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string id = e.item.cells[0].text;
string sql ="delete from tabname where id="+id;
.....
//以上连接数据库
cmd.ExecuteNonQuery();
cmd.Dispose();
con.close();
bind();//重新绑定
}
CS0122: 不可访问“System.Web.UI.WebControls.DataGridCommandEventArgs.item”,因为它受保护级别限制
private void myDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string id = e.item.cells[0].text;
string sql ="DELETE FROM customer WHERE uid='"+id+"'";
string strConnection = "server=CHEYO;";
strConnection += "database=bookstore;uid=sa;password=vv7g51;";
SqlConnection objConnection = new SqlConnection(strConnection);
SqlCommand objCmd = new SqlCommand(strSQL,objConnection);
objCmd.ExecuteNonQuery();
cmd.Dispose();
objConnection.close();
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}分不够可以加.请各位帮帮我!
objDataAdapter是哪裡來的啊?還有......
private void myDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
String Sql="DELETE FROM customer WHERE uid='"+e.Item.Cells[0].Text+"'";
string strConnection = "server=CHEYO;";
strConnection += "database=bookstore;uid=sa;password=vv7g51";
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand objCmd = new SqlCommand(Sql,objConnection);
objCmd.ExecuteNonQuery();
objcmd.Dispose();
objConnection.Close();
string strSQL="select uid,id 用户名,passwd 密码,name,email,phone,idcard,address from customer order by uid asc;";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,objConnection);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
MyDataGrid.DataSource = objDataSet.Tables["customer"].DefaultView;
MyDataGrid.DataBind();
}
现在编译没错.但是点击按钮没有只相当于刷新一次页面,没有从表中删除.数据库里的数据
也没改变. :(1.aspx:<%@ Page Language="c#" Src="1.aspx.cs" Inherits="myTest" %>
<html>
<body>
<form runat="server">
<asp:DataGrid id="myDataGrid" runat="server" BorderColor="#0066cc" BorderStyle="Dashed" BorderWidth="1px" BackColor="White" CellPadding="4"
ForeColor="Salmon" Font-Size="X-Small">
<AlternatingItemStyle BackColor="#ffeeef"></AlternatingItemStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="#663399"
BackColor="#FFCC66"></SelectedItemStyle>
<ItemStyle BorderWidth="2px" ForeColor="#ff8000" BorderStyle="Dashed"
BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" BorderWidth="1px" ForeColor="white"
BackColor="Orange"></HeaderStyle>
<FooterStyle ForeColor="Maroon" BackColor="#FFFFCC"></FooterStyle>
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="white"></PagerStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Button id="btnDelete" runat="server" Text="Button" CommandName="Delete"></asp:Button>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid></form>
</body>
</html>
1.aspx.cs:using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public class myTest:Page
{
//private DataSet ds = new DataSet();
public DataGrid myDataGrid;
void Page_load(object sender, EventArgs e)
{
string strConnection = "server=CHEYO;";
strConnection += "database=bookstore;uid=sa;password=vv7g51;";
string strSQL="select uid,id 用户名,passwd 密码,name,email,phone,idcard,address from customer order by uid asc;";
SqlConnection objConnection = new SqlConnection(strConnection);
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,strConnection);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}
private void myDataGrid_DeleteCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
String Sql="DELETE FROM customer WHERE uid='"+e.Item.Cells[0].Text+"'";
string strConnection = "server=CHEYO;";
strConnection += "database=bookstore;uid=sa;password=vv7g51";
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand objCmd = new SqlCommand(Sql,objConnection);
objCmd.ExecuteNonQuery();
objCmd.Dispose();
objConnection.Close();
string strSQL="select uid,id 用户名,passwd 密码,name,email,phone,idcard,address from customer order by uid asc;";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,objConnection);
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
myDataGrid.DataSource = objDataSet.Tables["customer"].DefaultView;
myDataGrid.DataBind();
}
}
如果不用和數據庫打交道,只是與DataTable打交道,就很簡單了!以下供參考:
DTable.Rows[e.Item.ItemIndex].Delete();//DTable為前面定義並賦值的DataTable
DGrid.DataSource=DTable.DefaultView;
DGrid.DataBind();
提出幾點建議:
1.我寫的沒有根據你的整體程序進行分層編寫,建議你考慮使用,這樣代碼會比較有層次,結構清晰;
2.能公用的代碼儘量用類別或函數來寫,然後調用,不要使用時又重複編寫代碼.比如數據庫連接的代碼等.
3.以後再寫...:)
不過你的刪除按鈕好像是在左邊,所以Delete代碼中的e.Item.Cells[0].Text就應該相應地改為e.Item.Cells[1].Text;
如果不行,你的DataGrid就先照我寫的試試:
<asp:DataGrid ID="DGrid" Runat="server">
<Columns>
<asp:ButtonColumn Text="編輯" HeaderText="編輯" CommandName="Edit"></asp:ButtonColumn>
<asp:ButtonColumn Text="刪除" HeaderText="刪除" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
當然,編輯那一列要編寫相應的代碼才會有效果;刪除的話,就要將e.Item.Cells[0].Text相應地改為e.Item.Cells[2].Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public class myTest:Page
{
//private DataSet ds = new DataSet();
public DataGrid myDataGrid;
private string strConnection = "server=CHEYO ;database=bookstore;uid=sa;password=vv7g51;";
void Page_load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GridBind();
}
}
/// <summary>
/// SqlConnection对象
/// </summary>
/// <returns></returns>
private SqlConnection getConn()
{
SqlConnection objConnection = new SqlConnection(this.strConnection);
return objConnection;
}
/// <summary>
/// 绑定到datagrid
/// </summary>
private void GridBind()
{
string strSQL="select uid,id 用户名,passwd 密码,name,email,phone,idcard,address from customer order by uid asc;";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,getConn());
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}
/// <summary>
/// 删除记录操作
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void myDataGrid_DeleteCommand(object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName=="Delete")
{
String Sql="DELETE FROM customer WHERE uid='"+e.Item.Cells[0].Text+"'";
SqlConnection objConnection =this.getConn();
objConnection.Open();
SqlCommand objCmd = new SqlCommand(Sql,objConnection);
objCmd.ExecuteNonQuery();
objCmd.Dispose();
objConnection.Close();
}
//bind data to datagrid again
this.GridBind();
}
}
我试了一下你刚刚整理的代码.
结果如下:
编译成功.但是点击按钮时没有任何的反应相当于只刷新了一下页面.
我试着把
Response.Write("hehe");
写到Page_load(),getConn(),GridBind()这几个方法里(这应该叫方法吧? 第一次接触面向对象的程序设计 -_-),都可以在页面上正常显示出来.
但写到myDataGrid_DeleteCommand()里,却没有显示出来.
看来问题就出在这了.
1.aspx页面中关于那个button的代码如下:
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Button id="btnDelete" runat="server" Text="Button" CommandName="Delete"></asp:Button>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
请问是什么原因.
谢谢了!
如果你是用ms viso studio .net 开发环境,请在code behind代码中,找出系统自动生成代码,加入删除事件的注册。如下:
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
//加入删除事件的注册绑定
this.myDataGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandle(this.myDataGrid_ItemCommand);
}
#endregion
否则在自己的初始化代码中,加入以上注册事件代码试一下,ok?
看了你的Button代碼,問題就在那裡!
為甚麼要使用樣板<asp:TemplateColumn>呢?用<asp:ButtonColumn>就可以了啊!
另外,你有沒有仔細看過我的回覆啊?我真的有點懷疑...
[以下引用]:**********
如果不行,你的DataGrid就先照我寫的試試:
<asp:DataGrid ID="myDataGrid" Runat="server">
<Columns>
<asp:ButtonColumn Text="編輯" HeaderText="編輯" CommandName="Edit"></asp:ButtonColumn>
<asp:ButtonColumn Text="刪除" HeaderText="刪除" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
當然,編輯那一列要編寫相應的代碼才會有效果;刪除的話,就要將e.Item.Cells[0].Text相應地改為e.Item.Cells[2].Text;
**********[引用結束]
如果你只需要"刪除",就把"編輯"那句去掉,再將e.Item.Cells[0].Text相應地改為e.Item.Cells[1].Text就行了!這樣是不會有問題的,有問題你找我!
寫在最後:別忘了多給點分哦!:P
如果你要使用樣板<asp:TemplateColumn>的話,可以採用在前端HTML中寫內嵌的C#代碼,然後在Button中調用就可以實現,比如:<asp:Button id="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click()">,只是麻煩一些!
我說的"關聯"的意思也就是billqi(bill)兄的意思;不過你使用的是樣板<asp:TemplateColumn>,billqi(bill)兄的方法並不能解決你的問題!
对于ffj521(古剑‧酒)提出的方法,我取消了模板,最后,还是不行.我就在MSDN里狂搜
终于找到类似的了.
模仿着MSDN的例子.
终于在再次麻烦ffj521(古剑‧酒)前找搞定了.
真累.
之前种种方法失败的最主要原因是:
1.aspx中的 DataGrid里少加了个属性:OnItemCommand="myDataGrid_Command"谢谢以上各位的热心回复.特别是ffj521(古剑‧酒).太谢谢你了!
ffj521有空帮我看看这个: :)
http://expert.csdn.net/Expert/topic/2350/2350261.xml?temp=.5788538我把结果帖在这:
----删除:
1.aspx:
<%@ Page Language="c#" Src="1.aspx.cs" Inherits="myTest" %>
<%@ Register TagPrefix="UserControl" TagName="Header" Src="header.ascx" %>
<UserControl:Header id="MyHeader" runat="server" />
<html>
<body>
<div align="center">
<form runat="server">
<asp:DataGrid id="myDataGrid" runat="server" BorderColor="#0066cc" BorderStyle="Dashed" BorderWidth="1px" BackColor="White" CellPadding="4"
ForeColor="Salmon" Font-Size="X-Small" OnItemCommand="myDataGrid_Command">
<AlternatingItemStyle BackColor="#ffeeef"></AlternatingItemStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="#663399"
BackColor="#FFCC66"></SelectedItemStyle>
<ItemStyle BorderWidth="2px" ForeColor="#ff8000" BorderStyle="Dashed"
BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" BorderWidth="1px" ForeColor="white"
BackColor="Orange"></HeaderStyle>
<FooterStyle ForeColor="Maroon" BackColor="#FFFFCC"></FooterStyle>
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="white"></PagerStyle>
<Columns>
<asp:ButtonColumn HeaderText="操作" ButtonType="LinkButton" Text="删除" CommandName="Delete"/></Columns>
</asp:DataGrid>
</form>
</div>
</body>
</html>1.aspx.cs:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public class myTest:Page
{
public DataGrid myDataGrid;
private string strConnection = "server=CHEYO;database=bookstore;uid=sa;password=vv7g51;";
void Page_load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GridBind();
}
}
private SqlConnection getConn()
{
SqlConnection objConnection = new SqlConnection(this.strConnection);
return objConnection;
} private void GridBind()
{ string strSQL="select uid,id,passwd,name,email,phone from customer order by uid asc;";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,getConn());
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}
public void myDataGrid_Command(Object sender, DataGridCommandEventArgs e)
{ switch(((LinkButton)e.CommandSource).CommandName)
{
case "Delete":
DeleteItem(e); break;
default: break;
}
}
void DeleteItem(DataGridCommandEventArgs e)
{ // e.Item is the table row where the command is raised. For bound
// columns, the value is stored in the Text property of a TableCell.
string tmpuid = e.Item.Cells[1].ToString();
string strSQL="DELETE FROM customer WHERE uid='"+e.Item.Cells[1].Text+"'";
SqlConnection objConnection =this.getConn();
objConnection.Open();
SqlCommand objCmd = new SqlCommand(strSQL,objConnection);
objCmd.ExecuteNonQuery();
objCmd.Dispose();
objConnection.Close();
GridBind();
}
}
1.aspx:
<%@ Page Language="c#" Src="1.aspx.cs" Inherits="myTest" %>
<%@ Register TagPrefix="UserControl" TagName="Header" Src="header.ascx" %>
<UserControl:Header id="MyHeader" runat="server" />
<html>
<body>
<div align="center">
<form runat="server">
<asp:DataGrid id="myDataGrid" runat="server" BorderColor="#0066cc" BorderStyle="Dashed" BorderWidth="1px" BackColor="White" CellPadding="4"
ForeColor="Salmon" Font-Size="X-Small" OnItemCommand="myDataGrid_Command" OnEditCommand="myDataGrid_Edit" OnCancelCommand="myDataGrid_Cancel" OnUpdateCommand="myDataGrid_Update">
<AlternatingItemStyle BackColor="#ffeeef"></AlternatingItemStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="#663399"
BackColor="#FFCC66"></SelectedItemStyle>
<ItemStyle BorderWidth="2px" ForeColor="#ff8000" BorderStyle="Dashed"
BackColor="White"></ItemStyle>
<HeaderStyle Font-Bold="True" BorderWidth="1px" ForeColor="white"
BackColor="Orange"></HeaderStyle>
<FooterStyle ForeColor="Maroon" BackColor="#FFFFCC"></FooterStyle>
<PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="white"></PagerStyle>
<Columns><asp:EditCommandColumn EditText="编辑" CancelText="取消" UpdateText="保存" HeaderText="操作"><ItemStyle Wrap="False"> </ItemStyle>
<HeaderStyle Wrap="False"></HeaderStyle></asp:EditCommandColumn>
<asp:ButtonColumn HeaderText="操作" ButtonType="LinkButton" Text="删除" CommandName="Delete"/></Columns>
</asp:DataGrid>
</form>
</div>
</body>
</html>1.aspx.cs:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public class myTest:Page
{
public DataGrid myDataGrid;
private string strConnection = "server=CHEYO;database=bookstore;uid=sa;password=vv7g51;";
void Page_load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
GridBind();
}
}
private SqlConnection getConn()
{
SqlConnection objConnection = new SqlConnection(this.strConnection);
return objConnection;
} private void GridBind()
{ string strSQL="select uid,id,passwd,name,email,phone from customer order by uid asc;";
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strSQL,getConn());
DataSet objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet,"customer");
DataView objDataView = new DataView(objDataSet.Tables["customer"]);
myDataGrid.DataSource = objDataView;
myDataGrid.DataBind();
}
public void myDataGrid_Command(Object sender, DataGridCommandEventArgs e)
{ switch(((LinkButton)e.CommandSource).CommandName)
{
case "Delete":
DeleteItem(e); break;
default: break;
}
}
void DeleteItem(DataGridCommandEventArgs e)
{ // e.Item is the table row where the command is raised. For bound
// columns, the value is stored in the Text property of a TableCell.
string tmpuid = e.Item.Cells[1].ToString();
string strSQL="DELETE FROM customer WHERE uid='"+e.Item.Cells[2].Text+"'";
SqlConnection objConnection =this.getConn();
objConnection.Open();
SqlCommand objCmd = new SqlCommand(strSQL,objConnection);
objCmd.ExecuteNonQuery();
objCmd.Dispose();
objConnection.Close();
GridBind();
}
public void myDataGrid_Edit(Object sender, DataGridCommandEventArgs e)
{ myDataGrid.EditItemIndex = e.Item.ItemIndex;
GridBind();
}
public void myDataGrid_Cancel(Object sender, DataGridCommandEventArgs e)
{
myDataGrid.EditItemIndex = -1;
GridBind();
} public void myDataGrid_Update(Object sender, DataGridCommandEventArgs e)
{
TextBox UID = (TextBox)e.Item.Cells[2].Controls[0];
TextBox Passwd = (TextBox)e.Item.Cells[4].Controls[0];
TextBox Name = (TextBox)e.Item.Cells[5].Controls[0]; string strSQL="UPDATE customer SET passwd = '"+Passwd.Text+"',name = '"+Name.Text+"' WHERE uid='"+UID.Text+"'";
SqlConnection objConnection =this.getConn();
objConnection.Open();
SqlCommand objCmd = new SqlCommand(strSQL,objConnection);
objCmd.ExecuteNonQuery();
objCmd.Dispose();
objConnection.Close();
myDataGrid.EditItemIndex = -1;
GridBind();
}
}
:(
这次给ffj521(古剑‧酒) 50
下次多点
:)