<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        動態組合SQL語句方式實現批量更新的實例

        來源:懂視網 責編:小采 時間:2020-11-27 22:41:30
        文檔

        動態組合SQL語句方式實現批量更新的實例

        動態組合SQL語句方式實現批量更新的實例: Default.aspx 代碼如下:<%@ Page Language=C# AutoEventWireup=true CodeFile=Index.aspx.cs Inherits=Index %> <!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional/
        推薦度:
        導讀動態組合SQL語句方式實現批量更新的實例: Default.aspx 代碼如下:<%@ Page Language=C# AutoEventWireup=true CodeFile=Index.aspx.cs Inherits=Index %> <!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional/

        Default.aspx

        代碼如下:
        <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

        <!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>供求信息網審核發布信息</title>
        </head>
        <body class="Font">
            <form id="form1" runat="server">
            <div style="text-align: left" align="left"><asp:Panel ID="Panel2" runat="server">
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    OnRowDataBound="GridView1_RowDataBound"
                    OnSelectedIndexChanging="GridView1_SelectedIndexChanging" Font-Size="9pt"
                    AllowPaging="True" EmptyDataText="沒有相關數據可以顯示!"
                    OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4"
                    ForeColor="#333333" GridLines="None" DataKeyNames="id">
                        <Columns>
                             <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:CheckBox ID="cbSingleOrMore" runat="server" />
                                        </ItemTemplate>
                              </asp:TemplateField>
                            <asp:BoundField DataField="id" HeaderText="信息ID" />
                            <asp:BoundField DataField="name" HeaderText="信息主題" />
                            <asp:BoundField DataField="type" HeaderText="信息分類" />
                            <asp:BoundField DataField="content" HeaderText="發布內容" />
                            <asp:BoundField DataField="userName" HeaderText="發布人" />
                            <asp:BoundField DataField="lineMan" HeaderText="聯系人" />
                            <asp:BoundField DataField="issueDate" HeaderText="發布時間"
                                DataFormatString="{0:d}" />
                        </Columns>
                        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Right" />
                        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                </asp:Panel>
                            <asp:CheckBox ID="cbAll" runat="server" AutoPostBack="True"
                    Font-Size="9pt" OnCheckedChanged="cbAll_CheckedChanged"
                                Text="全選/反選" />

                <asp:Button ID="btnUpdateTime" runat="server" onclick="btnUpdateTime_Click"
                    Text="更新發布時間" />

            </div>
            </form>
        </body>
        </html>

        Default.aspx.cs

        代碼如下:

        using System;
        using System.Data;
        using System.Configuration;
        using System.Collections;
        using System.Web;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;

        using System.Text;
        using System.Data.SqlClient;

        public partial class Index : System.Web.UI.Page
        {
            SqlConnection sqlcon;
            string strCon = ConfigurationManager.AppSettings["conStr"];
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    this.GV_DataBind();
                }

            }
            public void GV_DataBind()
            {
                string sqlstr = "select * from tb_inf";
                sqlcon = new SqlConnection(strCon);
                SqlDataAdapter da = new SqlDataAdapter(sqlstr, sqlcon);
                DataSet ds = new DataSet();
                sqlcon.Open();
                da.Fill(ds, "tb_inf");
                sqlcon.Close();
                this.GridView1.DataSource = ds;
                this.GridView1.DataKeyNames = new string[] { "id" };
                this.GridView1.DataBind();
                if (GridView1.Rows.Count > 0)
                {
                    return;//有數據,不要處理
                }
                else//顯示表頭并顯示沒有數據的提示信息
                {
                    StrHelper.GridViewHeader(GridView1);
                }
            }
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string gIntro = e.Row.Cells[4].Text;
                    e.Row.Cells[4].Text = StrHelper.GetFirstString(gIntro, 12);
                }
            }
            protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
            {
                string id = this.GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
                sqlcon = new SqlConnection(strCon);
                SqlCommand com = new SqlCommand("select [check] from tb_inf where id='" + id + "'", sqlcon);
                sqlcon.Open();
                string count = Convert.ToString(com.ExecuteScalar());
                if (count == "False")
                {
                    count = "1";
                }
                else
                {
                    count = "0";
                }
                com.CommandText = "update tb_inf set [check]=" + count + " where id=" + id;
                com.ExecuteNonQuery();
                sqlcon.Close();
                this.GV_DataBind();
            }
            protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                this.GridView1.PageIndex = e.NewPageIndex;
                this.GV_DataBind();
            }
            protected void cbAll_CheckedChanged(object sender, EventArgs e)
            {
                for (int i = 0; i <= GridView1.Rows.Count - 1; i++)//遍歷
                {
                    CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("cbSingleOrMore");
                    if (cbAll.Checked == true)
                    {
                        cbox.Checked = true;
                    }
                    else
                    {
                        cbox.Checked = false;
                    }
                }
            }

            protected void btnUpdateTime_Click(object sender, EventArgs e)
            {
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (GridViewRow row in this.GridView1.Rows)//循環遍歷GridView控件中行,拼裝IN子句
                {
                    CheckBox cbox = row.FindControl("cbSingleOrMore") as CheckBox;
                    if (cbox.Checked)//判斷復選框是否被選中
                    {
                        //當數據行中的復選框被選中時,即將該行記錄的主鍵值放入IN子句中
                        builder.AppendFormat("'{0}',", this.GridView1.DataKeys[row.RowIndex].Value.ToString());
                        i++;
                        continue;
                    }
                    continue;
                }
                if (builder.ToString().Length == 0)//當IN子句中沒有任何數據行,則彈出提示
                {
                    StrHelper.Alert("沒有選中任何數據行,請重新選擇!");
                    return;
                }
                //移除StringBuilder對象中的最后一個“,”
                builder.Remove(builder.ToString().LastIndexOf(","), 1);
                //拼裝SQL語句
                string SqlBuilderCopy = string.Format("Update tb_inf set issueDate='{0}' WHERE id IN ({1})", DateTime.Now.ToString(), builder.ToString());
                sqlcon = new SqlConnection(strCon);//創建數據庫連接
                SqlCommand sqlcom;//創建命令對象變量
                int result = 0;
                if (sqlcon.State.Equals(ConnectionState.Closed))
                    sqlcon.Open();//打開數據庫連接
                sqlcom = new SqlCommand(SqlBuilderCopy, sqlcon);
                SqlTransaction tran = sqlcon.BeginTransaction();//實例化事務,注意實例化事務必須在數據庫連接開啟狀態下
                sqlcom.Transaction = tran;//將命令對象與連接對象關聯
                try
                {
                    result = sqlcom.ExecuteNonQuery();//接收影響的行數
                    tran.Commit();//提交事務
                }
                catch (SqlException ex)
                {
                    StrHelper.Alert(string.Format("SQL語句發生了異常,異常如下所示:\n{0}", ex.Message));
                    tran.Rollback();//出現異常,即回滾事務,防止出現臟數據
                    return;
                }
                finally
                {
                    sqlcon.Close();
                }
                if (result == i)//判斷影響行數是否等于選中的數據行
                {
                    StrHelper.Alert("數據更新成功!");
                }
                else
                {
                    StrHelper.Alert("數據更新失敗,事務已回滾!");
                }
                GV_DataBind();//重新綁定控件數據
                return;
            }
        }

        StrHelper.cs

        代碼如下:

        using System;
        using System.Data;
        using System.Configuration;
        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.Text.RegularExpressions;
        using System.Text;

        /// <summary>
        ///StrHelper 的摘要說明
        /// </summary>
        public class StrHelper
        {
            public StrHelper(){}
            /// <summary>
            /// 截取字符串函數
            /// </summary>
            /// <param name="str">所要截取的字符串</param>
            /// <param name="num">截取字符串的長度</param>
            /// <returns></returns>
            static public string GetSubString(string str, int num)
            {
                #region
                return (str.Length > num) ? str.Substring(0, num) + "..." : str;
                #endregion
            }
            /// <summary>
            /// 截取字符串優化版
            /// </summary>
            /// <param name="stringToSub">所要截取的字符串</param>
            /// <param name="length">截取字符串的長度</param>
            /// <returns></returns>
            public static string GetFirstString(string stringToSub, int length)
            {
                #region
                Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
                char[] stringChar = stringToSub.ToCharArray();
                StringBuilder sb = new StringBuilder();
                int nLength = 0;
                bool isCut = false;
                for (int i = 0; i < stringChar.Length; i++)
                {
                    if (regex.IsMatch((stringChar[i]).ToString()))//regex.IsMatch指示正則表達式在輸入字符串中是否找到匹配項
                    {
                        sb.Append(stringChar[i]);//將信息追加到當前 StringBuilder 的結尾
                        nLength += 2;
                    }
                    else
                    {
                        sb.Append(stringChar[i]);
                        nLength = nLength + 1;
                    }
                    if (nLength > length)//替換字符串
                    {
                        isCut = true;
                        break;
                    }
                }
                if (isCut)
                    return sb.ToString() + "...";
                else
                    return sb.ToString();
                #endregion
            }
            /// 彈出JavaScript小窗口
            /// </summary>
            /// <param name="js">窗口信息</param>
            public static void Alert(string message)
            {
                #region
                string js = @"<Script language='JavaScript'>
                            alert('" + message + "');</Script>";
                HttpContext.Current.Response.Write(js);

                #endregion
            }
            public static void GridViewHeader(GridView gdv)//顯示表頭并顯示沒有數據的提示信息
            {
                //表頭的設置
                GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                foreach (DataControlField field in gdv.Columns)
                {
                    TableCell cell = new TableCell();
                    cell.Text = field.HeaderText;
                    cell.Width = field.HeaderStyle.Width;
                    cell.Height = field.HeaderStyle.Height;
                    cell.ForeColor = field.HeaderStyle.ForeColor;
                    cell.Font.Size = field.HeaderStyle.Font.Size;
                    cell.Font.Bold = field.HeaderStyle.Font.Bold;
                    cell.Font.Name = field.HeaderStyle.Font.Name;
                    cell.Font.Strikeout = field.HeaderStyle.Font.Strikeout;
                    cell.Font.Underline = field.HeaderStyle.Font.Underline;
                    cell.BackColor = field.HeaderStyle.BackColor;
                    cell.VerticalAlign = field.HeaderStyle.VerticalAlign;
                    cell.HorizontalAlign = field.HeaderStyle.HorizontalAlign;
                    cell.CssClass = field.HeaderStyle.CssClass;
                    cell.BorderColor = field.HeaderStyle.BorderColor;
                    cell.BorderStyle = field.HeaderStyle.BorderStyle;
                    cell.BorderWidth = field.HeaderStyle.BorderWidth;
                    row.Cells.Add(cell);
                }
                TableItemStyle headStyle = gdv.HeaderStyle;
                TableItemStyle emptyStyle = gdv.EmptyDataRowStyle;
                emptyStyle.Width = headStyle.Width;
                emptyStyle.Height = headStyle.Height;
                emptyStyle.ForeColor = headStyle.ForeColor;
                emptyStyle.Font.Size = headStyle.Font.Size;
                emptyStyle.Font.Bold = headStyle.Font.Bold;
                emptyStyle.Font.Name = headStyle.Font.Name;
                emptyStyle.Font.Strikeout = headStyle.Font.Strikeout;
                emptyStyle.Font.Underline = headStyle.Font.Underline;
                emptyStyle.BackColor = headStyle.BackColor;
                emptyStyle.VerticalAlign = headStyle.VerticalAlign;
                emptyStyle.HorizontalAlign = headStyle.HorizontalAlign;
                emptyStyle.CssClass = headStyle.CssClass;
                emptyStyle.BorderColor = headStyle.BorderColor;
                emptyStyle.BorderStyle = headStyle.BorderStyle;
                emptyStyle.BorderWidth = headStyle.BorderWidth;
                //空白行的設置
                GridViewRow row1 = new GridViewRow(0, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
                TableCell cell1 = new TableCell();
                cell1.Text = "沒有相關數據可以顯示!";
                cell1.BackColor = System.Drawing.Color.White;
                row1.Cells.Add(cell1);
                cell1.ColumnSpan = 6;//合并列
                if (gdv.Controls.Count == 0)
                {
                    gdv.Page.Response.Write("<script language='javascript'>alert('必須在初始化表格類之前執行DataBind方法并設置EmptyDataText屬性不為空!');</script>");
                }
                else
                {
                    gdv.Controls[0].Controls.Clear();
                    gdv.Controls[0].Controls.AddAt(0, row);
                    gdv.Controls[0].Controls.AddAt(1, row1);
                }
            }
        }

        聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        動態組合SQL語句方式實現批量更新的實例

        動態組合SQL語句方式實現批量更新的實例: Default.aspx 代碼如下:<%@ Page Language=C# AutoEventWireup=true CodeFile=Index.aspx.cs Inherits=Index %> <!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional/
        推薦度:
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 黄色免费网站在线看| 亚洲伊人久久大香线蕉影院| 免费无码专区毛片高潮喷水 | 国产成人综合亚洲绿色| 性色av免费观看| 亚洲Av永久无码精品一区二区| 久久电影网午夜鲁丝片免费| 亚洲av一本岛在线播放| 免费看韩国黄a片在线观看| 亚洲AV无码无限在线观看不卡| 午夜视频在线在免费| 黄色毛片免费网站| 亚洲无线观看国产精品| 日韩人妻一区二区三区免费| 亚洲国产成人久久77| 免费无码又爽又刺激毛片| 无人视频在线观看免费播放影院| 亚洲精品美女久久久久99小说| 中国毛片免费观看| 亚洲视频在线播放| 四虎成人精品一区二区免费网站| 免费一级毛片在线播放视频免费观看永久| 亚洲精品无码AV中文字幕电影网站| 久久国产一片免费观看| 亚洲精品mv在线观看| 免费看少妇作爱视频| 两个人日本免费完整版在线观看1| 久久亚洲AV成人无码国产| 午夜毛片不卡高清免费| 国产99精品一区二区三区免费| 亚洲视频网站在线观看| 国产男女猛烈无遮档免费视频网站 | 精品日韩亚洲AV无码一区二区三区| 免费人成在线视频| 4hu四虎免费影院www| 亚洲区视频在线观看| 久久精品亚洲乱码伦伦中文| 色片在线免费观看| 深夜A级毛片视频免费| 亚洲欧洲精品久久| 亚洲日韩人妻第一页|