Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > .NET Framework > Forum > ลบข้อมูลจาก Checkbox แบบ Array ไม่ใช่การ วนลูปเพื่อลบ



 

ลบข้อมูลจาก Checkbox แบบ Array ไม่ใช่การ วนลูปเพื่อลบ

 



Topic : 034234



โพสกระทู้ ( 9 )
บทความ ( 0 )



สถานะออฟไลน์




------>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>
&nbsp;
        <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>
&nbsp;
        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
&nbsp;
        <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 : - - - -







Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2009-11-11 16:31:43 By : ธนชล View : 2153 Reply : 3
 

 

No. 1



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook

ดูตัวอย่างนี้น่ะครับ ASP.NET Microsoft Access Multiple Checkbox Delete Record






Date : 2009-11-11 21:32:24 By : webmaster
 


 

No. 2



โพสกระทู้ ( 9 )
บทความ ( 0 )



สถานะออฟไลน์


ขอบคุณครับ ทำได้แล้วครับ

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 : ธนชล
 

 

No. 3



โพสกระทู้ ( 179 )
บทความ ( 0 )



สถานะออฟไลน์


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
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : ลบข้อมูลจาก Checkbox แบบ Array ไม่ใช่การ วนลูปเพื่อลบ
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 05
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่