Instances that dynamically combine SQL statements for batch update

Source: Internet
Author: User

Default. aspx

Copy codeThe Code is as follows: <% @ 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> Supply and Demand Information Network review and release information </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 = "no relevant data can be displayed! "
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 = "Information ID"/>
<Asp: BoundField DataField = "name" HeaderText = "info topic"/>
<Asp: BoundField DataField = "type" HeaderText = "Information Classification"/>
<Asp: BoundField DataField = "content" HeaderText = "published content"/>
<Asp: BoundField DataField = "userName" HeaderText = "publisher"/>
<Asp: BoundField DataField = "lineMan" HeaderText = "Contact"/>
<Asp: BoundField DataField = "issueDate" HeaderText = "Release Date"
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 = "select all/reselect"/>

<Asp: Button ID = "btnUpdateTime" runat = "server" onclick = "btnUpdateTime_Click"
Text = "update release time"/>

</Div>
</Form>
</Body>
</Html>

Default. aspx. cs

Copy codeThe Code is as follows:

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. receivettings ["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; // if there is data, do not process it
}
Else // displays the header with no data prompt
{
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 gridviewincluselectedindexchanging (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 ++) // traverse
{
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) // cyclically traverses the row IN the GridView control and assembles the in Clause
{
CheckBox cbox = row. FindControl ("cbSingleOrMore") as CheckBox;
If (cbox. Checked) // determines whether the check box is selected
{
// When the check box IN the Data row is selected, put the primary key value recorded IN the row into the IN Clause
Builder. AppendFormat ("'{0}',", this. GridView1.DataKeys [row. RowIndex]. Value. ToString ());
I ++;
Continue;
}
Continue;
}
If (builder. ToString (). Length = 0) // if no data row exists IN the IN clause, a prompt is displayed.
{
StrHelper. Alert ("no data row is selected. Please reselect it! ");
Return;
}
// Remove the last "," in the StringBuilder object
Builder. Remove (builder. ToString (). LastIndexOf (","), 1 );
// Assemble SQL statements
String SqlBuilderCopy = string. format ("Update tb_inf set issueDate = '{0}' WHERE id IN ({1})", DateTime. now. toString (), builder. toString ());
Sqlcon = new SqlConnection (strCon); // create a database connection
SqlCommand sqlcom; // create a command object variable
Int result = 0;
If (sqlcon. State. Equals (ConnectionState. Closed ))
Sqlcon. Open (); // Open the database connection
Sqlcom = new SqlCommand (SqlBuilderCopy, sqlcon );
SqlTransaction tran = sqlcon. BeginTransaction (); // instantiate the transaction. Note that the instantiated transaction must be in the database connection enabled state.
Sqlcom. Transaction = tran; // associate the command object with the connection object
Try
{
Result = sqlcom. ExecuteNonQuery (); // The number of rows affected by the receipt
Tran. Commit (); // submit the transaction
}
Catch (SqlException ex)
{
StrHelper. Alert (string. Format ("an exception occurred in the SQL statement. The exception is as follows: \ n {0}", ex. Message ));
Tran. Rollback (); // an exception occurs, that is, the transaction is rolled back to prevent dirty data.
Return;
}
Finally
{
Sqlcon. Close ();
}
If (result = I) // determine whether the number of affected rows is equal to the selected data rows
{
StrHelper. Alert ("data update successful! ");
}
Else
{
StrHelper. Alert ("data update failed, Transaction rolled back! ");
}
GV_DataBind (); // rebind Control Data
Return;
}
}

StrHelper. cs

Copy codeThe Code is as follows:

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;
// Introduce the following namespace
Using System. Text. RegularExpressions;
Using System. Text;

/// <Summary>
/// Summary of StrHelper
/// </Summary>
Public class StrHelper
{
Public StrHelper (){}
/// <Summary>
/// Truncates string functions
/// </Summary>
/// <Param name = "str"> string to be intercepted </param>
/// <Param name = "num"> extract the length of a string </param>
/// <Returns> </returns>
Static public string GetSubString (string str, int num)
{
# Region
Return (str. Length> num )? Str. Substring (0, num) + "...": str;
# Endregion
}
/// <Summary>
/// Extract the optimized string version
/// </Summary>
/// <Param name = "stringToSub"> string to be intercepted </param>
/// <Param name = "length"> extract the length of a string </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 indicates whether the regular expression matches the string.
{
Sb. Append (stringChar [I]); // Append the information to the end of the current StringBuilder
NLength + = 2;
}
Else
{
Sb. Append (stringChar [I]);
NLength = nLength + 1;
}
If (nLength> length) // Replace the string
{
IsCut = true;
Break;
}
}
If (isCut)
Return sb. ToString () + "...";
Else
Return sb. ToString ();
# Endregion
}
/// A small JavaScript window is displayed.
/// </Summary>
/// <Param name = "js"> window Information </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) // display the header and prompt information without data
{
// Set the header
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;
// Blank row settings
GridViewRow row1 = new GridViewRow (0,-1, DataControlRowType. EmptyDataRow, DataControlRowState. Normal );
TableCell cell1 = new TableCell ();
Cell1.Text = "no relevant data can be displayed! ";
Cell1.BackColor = System. Drawing. Color. White;
Row1.Cells. Add (cell1 );
Cell1.ColumnSpan = 6; // merge Columns
If (gdv. Controls. Count = 0)
{
Gdv. Page. Response. Write ("<script language = 'javascript '> alert (' The DataBind method must be executed before the table class is initialized and the EmptyDataText attribute is set to not empty! '); </Script> ");
}
Else
{
Gdv. Controls [0]. Controls. Clear ();
Gdv. Controls [0]. Controls. AddAt (0, row );
Gdv. Controls [0]. Controls. AddAt (1, row1 );
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.