|
|
|
ลบข้อมูลจาก Checkbox แบบ Array ไม่ใช่การ วนลูปเพื่อลบ |
|
|
|
|
|
|
|
------>Default.aspx
<%@ 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>DemoGridViewPage</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblSearch" runat="server" Text="Search By"></asp:Label>
<asp:DropDownList ID="ddlSearch" runat="server" style="margin-left: 0px">
<asp:ListItem Selected="True" Value="0">customer ID</asp:ListItem>
<asp:ListItem Value="1">Customer Name</asp:ListItem>
<asp:ListItem Value="2">Contact Name</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" onclick="btnSearch_Click"
Text="Search" />
<br />
<asp:GridView ID="gvSearch" runat="server" DataKeyNames="CustomerID"
ShowFooter="True" AllowPaging="True" AllowSorting="True" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
AutoGenerateColumns="False"
onpageindexchanging="gvSearch_PageIndexChanging" onsorting="gvSearch_Sorting">
<RowStyle ForeColor="#000066" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName"
SortExpression="ContactName" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Country" HeaderText="Country"
SortExpression="Country" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
SortExpression="PostalCode" />
<asp:BoundField DataField="Region" HeaderText="Region"
SortExpression="Region" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Nwind.mdb"
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [Fax], [Phone], [Country], [PostalCode], [Region], [City] FROM [Customers]">
</asp:AccessDataSource>
<br />
<asp:Label ID="lblError" runat="server" Text="lblShowError"></asp:Label>
</div>
<asp:TextBox ID="txtShowSQL" runat="server" Width="300px" ReadOnly="true">txtShowSQL</asp:TextBox>
</form>
</body>
</html>
Code (C#)------>Default.aspx.cs
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
//Define global Connection String
string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/Visual Studio 2008/WebSites/DemoGridview/App_Data/Nwind.mdb";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["sortOrder"] = "";
BindData("","");
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store
//IDs of records to be deleted
//StringCollection idCollection = new StringCollection();
OleDbConnection con = new OleDbConnection(strConnection);
OleDbCommand cmd=new OleDbCommand();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < gvSearch.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)gvSearch.Rows[i].Cells[0].FindControl("chkSelect");//แปลงค่าของเช็คบอค ตาม rows และ cell ที่เลือก
string strIDs = gvSearch.Rows[i].Cells[1].Text;
if (chkDelete.Checked)
{
if (con.State== ConnectionState.Open)
con.Close();
con.Open();
string sqlSql01 = "DELETE FROM Orders WHERE CustomerID='" + strIDs + "'";//ต้องการแก้ไขส่วนนี้ให้ ลบ แบบ array
string strSql = "DELETE FROM Customers WHERE CustomerID='" + strIDs + "'";
cmd = new OleDbCommand(sqlSql01, con);
cmd.ExecuteNonQuery();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
con.Close();
}
BindData("", "");
// rebind the GridView
gvSearch.DataBind();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindData("","");
}
void BindData(string sortExp, string sortDir)
{
try
{
string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/Visual Studio 2008/WebSites/DemoGridview/App_Data/Nwind.mdb";
OleDbConnection ObjConn = new OleDbConnection();
OleDbCommand ObjComm = new OleDbCommand();
OleDbDataAdapter DtAdapter = new OleDbDataAdapter();
DataSet Dts = new DataSet();
string StrSql = string.Empty;
string StrReplace = txtSearch.Text.Replace("'", "''");
switch (ddlSearch.SelectedValue)
{
case "0":
StrSql = "SELECT * FROM Customers WHERE (CustomerID LIKE '%" + StrReplace + "%')";
break;
case "1":
StrSql = "SELECT * FROM Customers WHERE (CompanyName LIKE '%" + StrReplace + "%')";
break;
case "2":
StrSql = "SELECT * FROM Customers WHERE (ContactName LIKE '%" + StrReplace + "%')";
break;
}
ObjConn.ConnectionString = strConnection;
ObjComm.Connection = ObjConn;
ObjComm.CommandText = StrSql;
ObjComm.CommandType = CommandType.Text;
DtAdapter.SelectCommand = ObjComm;
DtAdapter.Fill(Dts);
DataView dv = new DataView();
dv = Dts.Tables[0].DefaultView;
if (sortExp != string.Empty)
{
dv.Sort = string.Format("{0} {1}", sortExp, sortDir);
}
gvSearch.DataSource = Dts;
gvSearch.DataSource = dv;
gvSearch.DataBind();
DtAdapter = null;
ObjConn.Close();
ObjConn = null;
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void gvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSearch.PageIndex = e.NewPageIndex;
BindData("", "");
}
protected void gvSearch_Sorting(object sender, GridViewSortEventArgs e)
{
BindData(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
}
Tag : - - - -
|
|
|
|
|
|
Date :
2009-11-11 16:31:43 |
By :
ธนชล |
View :
2212 |
Reply :
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ขอบคุณครับ ทำได้แล้วครับ
Code (C#)
protected void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store
//IDs of records to be deleted
StringCollection idCollection = new StringCollection();
ObjConn = new OleDbConnection(strConnection);
string strIDs = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < gvSearch.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)gvSearch.Rows[i].Cells[0].FindControl("chkSelect");//แปลงค่าของเช็คบอค ตาม rows และ cell ที่เลือก
if (chkDelete.Checked)
{
string strID = gvSearch.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
gvSearch.DataBind();
}
/// <summary>
/// This is to Delete multiple records in gridview
/// </summary>
/// <param name="idCollection">stringCollection</param>
private void DeleteMultipleRecords(StringCollection idCollection)
{
ObjConn = new OleDbConnection(strConnection);
ObjComm = new OleDbCommand();
string IDs = string.Empty;
foreach (string id in idCollection)
{
IDs += "'" + id.ToString() + "',";
}
try
{
string strIDs = IDs.Substring(0, IDs.LastIndexOf(","));
if (ObjConn.State == ConnectionState.Open)
ObjConn.Close();
ObjConn.Open();
string sqlSql01 = "DELETE FROM Orders WHERE CustomerID IN (" + strIDs + ")'";
string SqlStr = "DELETE FROM Customers WHERE CustomerID IN (" + strIDs + ")'";
string sqlStr01Of = sqlSql01.Substring(0, sqlSql01.LastIndexOf("'"));
string sqlStrOf = SqlStr.Substring(0, SqlStr.LastIndexOf("'"));
ObjComm = new OleDbCommand(sqlStr01Of, ObjConn);
ObjComm.ExecuteNonQuery();
ObjComm.CommandType = CommandType.Text;
ObjComm.CommandText = sqlStrOf;
ObjComm.Connection = ObjConn;
ObjComm.ExecuteNonQuery();
}
catch (OleDbException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
ObjConn.Close();
BindData("", "");
}
|
|
|
|
|
Date :
2009-11-12 10:38:03 |
By :
ธนชล |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Code (C#)
StringCollection idCollection = new StringCollection();
ObjConn = new OleDbConnection(strConnection);
string strIDs = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < gvSearch.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)gvSearch.Rows[i].Cells[0].FindControl("chkSelect");//แปลงค่าของเช็คบอค ตาม rows และ cell ที่เลือก
if (chkDelete.Checked)
{
string strID = gvSearch.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
เปลี่ยนเป็นแบบนี้ก็ได้นะครับ ง่ายๆ ดี
Code (C#)
foreach (GridViewRow grv in gvSearch.Rows)
{
CheckBox chkDelete= (CheckBox)grv.FindControl("chkSelect");
if (chkDelete.Checked)
{
string strID = gvSearch.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
ลองดูนะครับ ^^
|
|
|
|
|
Date :
2009-11-12 13:14:19 |
By :
ksillapapan |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 00
|