遍历checkbox

前台页面

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Goodset.aspx.cs" Inherits="Module_ISS_Goodset" Title="商品状态页面" %>
<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div>
<table>
    <tr>
        <td>商品款号</td>
        <td><asp:TextBox ID="goodid" runat="server"></asp:TextBox></td>
        <td>商品名称</td>
        <td><asp:TextBox ID="goodsName" runat="server"></asp:TextBox></td>
        <td><asp:Button ID="seach" runat="server" Text="查询" οnclick="seach_Click" /></td>
    </tr>
</table>
     <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                                              CellPadding="4" ForeColor="#333333"
        GridLines="None" AllowPaging="True"
                                              AllowSorting="True"
        onrowdatabound="GridView1_RowDataBound" >
          <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
          <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
        <Columns>
             <asp:TemplateField HeaderText="热卖">
                <ItemTemplate>
                <asp:CheckBox ID="checktopid" runat="server" ToolTip='<%# Bind("fgoodsid") %>'
                        oncheckedchanged="checktopid_CheckedChanged" AutoPostBack="True"/>
                </ItemTemplate>           
            </asp:TemplateField>
            <asp:TemplateField HeaderText="新品">
                <ItemTemplate>
                <asp:CheckBox ID="checknewid" runat="server" ToolTip='<%# Bind("fgoodsid") %>'
                        oncheckedchanged="checknewid_CheckedChanged" AutoPostBack="True" />
                </ItemTemplate>           
            </asp:TemplateField>
             <asp:TemplateField HeaderText="推荐">
                <ItemTemplate>
                <asp:CheckBox ID="checkgoodsid" runat="server" ToolTip='<%# Bind("fgoodsid") %>'
                        oncheckedchanged="checkgoodsid_CheckedChanged" AutoPostBack="True" />
                </ItemTemplate>           
            </asp:TemplateField>
            <asp:BoundField DataField="fgoodsid" HeaderText="商品款号" />
            <asp:BoundField DataField="fgoodsname" HeaderText="商品款名" />
            </Columns>
                  <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                  <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                  <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                  <EditRowStyle BackColor="#2461BF" />
                  <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
          </ContentTemplate>
                </asp:UpdatePanel>
    <div style="float:left">
    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
    <ContentTemplate>
    <webdiyer:AspNetPager ID="AspNetPager1" runat="server"
                                              CssClass="pages" CurrentPageButtonClass="cpb"
            style="font-size:13px;" HorizontalAlign="Right" NumericButtonCount="6"
            NumericButtonTextFormatString="[{0}]"
            CustomInfoHTML="第 <font color='red'><b>%CurrentPageIndex%</b></font> 页 共 %PageCount% 页 显示 %StartRecordIndex%-%EndRecordIndex% 条"
            InputBoxStyle="width:64px; height:14px;" ShowInputBox="Always"
            SubmitButtonText=" GO " FirstPageText="[首 页]" PrevPageText="[上 页]"
            NextPageText="[下 页]" LastPageText="[末 页]" TextBeforeInputBox="转到第"
            TextAfterInputBox="页 " PagingButtonSpacing="10px" width="85%"
            ShowCustomInfoSection="Left" UrlPaging="true"
            OnPageChanging="AspNetPager1_PageChanging" ></webdiyer:AspNetPager></div>
  </ContentTemplate>
    </asp:UpdatePanel>
            </div>
           
</asp:Content>

 

 

 

后台页面

 

using System;
using System.Collections;
using System.Collections.Generic;
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.Data.SqlClient;

public partial class Module_ISS_Goodset : System.Web.UI.Page
{
    string flage = string.Empty;
            DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["FUserId"] = "admin";                     //用户id
        Session["FUserSeq"] = "2111862";
        Session["FUSERNAME"] = "系统管理员";

        Session["FDARSeq"] = "339";                     //用户id
        Session["FDARSNname"] = "技术部经理";
        Session["FDeptSName"] = "技术部";
        Session["FPostSName"] = "6-管理主管";
        Session["FOrgaSeq"] = "2";
        Session["fgoodsid"] = "";
        if (!IsPostBack) {
            Bind();
        }
       
    }
    /// <summary>
    /// 绑定事件
    /// </summary>
    public void Bind()
     {
         DAC dac = new DAC();
        string goodsid = this.goodid.Text.Trim(); //商品款号文本框获值
        string goodsname = this.goodsName.Text.Trim(); // 商品名称文本框获值
         string sql = "select FGOODSSEQ, FGOODSID,FGOODSNAME from TBDG_GOODS where ";

         if (goodsid != "")
        {
            sql += "     FGOODSID='" + goodsid + "' and";
        }
         if (goodsname != "")
        {
            sql += "    FGOODSNAME = '" + goodsname + "' and ";
        }
         sql += " 1 = 1";

         DataSet myds = dac.dataSet(sql);
        this.AspNetPager1.RecordCount = myds.Tables[0].Rows.Count;
         int pageIndex = this.AspNetPager1.CurrentPageIndex - 1;   ///第一页
         GridView1.DataSource = dac.GetCurrentPage(pageIndex, AspNetPager1.PageSize, sql, "TBDG_GOODS");
         GridView1.DataKeyNames = new string[] { "FGOODSSEQ" };
         GridView1.DataBind();


         foreach  (GridViewRow row  in GridView1.Rows)  // 遍历所有checkbox的状态
         {
             CheckBox box = row.Cells[0].Controls[1] as CheckBox;
              SetChecked(box.ToolTip);
        }
    }


    /// <summary>
    /// 遍历所有checkbox的状态
    /// </summary>
    /// <param name="id"></param>
    protected void SetChecked(string id)
   {

        DataTable dt2 = new DataTable();
        DAC dac = new DAC();
        string goodsid = this.goodid.Text.Trim(); //商品款号文本框获值
        string goodsname = this.goodsName.Text.Trim(); // 商品名称文本框获值
        string sql = string.Empty;
        if (goodsid != "" || goodsname != "") //如果文本框有值,进行查询的时候,要判断TBDG_GOODS表里和Goods_content表,Goods_content表里是否有TBDG_GOODS 相关联的fgoodsid
        {
             sql = "select tg.fgoodsname,tg.fgoodsid,g.* from TBDG_GOODS tg  left join Goods_content g on  tg.fgoodsid = g.fgoodsid where g.fgoodsid <> '' and ";
            if (goodsid != "")
            {
                sql += "     g.FGOODSID='" + goodsid + "' and ";
            }
            if (goodsname != "")
            {
                sql += "    tg.FGOODSNAME = '" + goodsname + "' and ";
            }
            sql += " 1 = 1";
        }
        else
        {
            sql = "select * from Goods_content order by id ";  //根据Goods_content表查询所有并按id升序
        }
     
        dt2 =  dac.GetDataSet(sql);

        for ( int i = 0; i < dt2.Rows.Count -1; i++)
        {
             DataRow row = dt2.Rows[i];

            if (row["fgoodsid"].Equals(id))
            {
                if (row["topstate"].Equals("1"))
                {
                    CheckBox box = GridView1.Rows[i].Cells[0].Controls[1] as CheckBox;
                    box.Checked = true;
                }
                 if (row["newstate"].Equals("1"))
                {
                    CheckBox box = GridView1.Rows[i].Cells[1].Controls[1] as CheckBox;
                    box.Checked = true;
                }
                 if (row["goodsstate"].Equals("1"))
                {
                    CheckBox box = GridView1.Rows[i].Cells[2].Controls[1] as CheckBox;
                    box.Checked = true;
                }
            }
          }
    }

    /// <summary>
    /// 分页事件
    /// </summary>
    /// <param name="src"></param>
    /// <param name="e"></param>
    protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        AspNetPager1.CurrentPageIndex = e.NewPageIndex;
        Bind();
    }

    /// <summary>
    /// TBDG_GOODS 实体类
    /// </summary>
    public class TBDG_GOODS
    {
        public int FGOODSSEQ { get; set; } //商品流水号
        public string FGOODSID { get; set; } //商品款号
        public string FGOODSNAME { get; set; } //商品名称
    }
    /// <summary>
    /// Goods_content 实体类
    /// </summary>
    public class Goods_content
    {
        public int id { get; set; } //商品状态流水号
        public string fgoodsid { get; set; } //商品款号
        public string topstate { get; set; } //热卖状态,默认为0,选择为1
        public string newstate { get; set; } //新品状态,默认为0,选择为1
        public string goodsstate { get; set; } //推荐状态,默认为0,选择为1
        public string special { get; set; } // 特价状态,默认为0,选择为1
    }

    /// <summary>
    /// 查询按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void seach_Click(object sender, EventArgs e)
    {
         Bind();
    }

 

    /// <summary>
    /// 鼠标移动到Gridview上面背景颜色改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int i;
        for (i = 0; i < this.GridView1.Rows.Count; i++)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#507CD1'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }

   

    }
    /// <summary>
    /// 修改新品状态
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void checknewid_CheckedChanged(object sender, EventArgs e)
    {
        DAC dac = new DAC();

        int a = 0;
        CheckBox box = sender as CheckBox;
        string sqlss = "select * from Goods_content where fgoodsid = '" + box.ToolTip + "'";
        ds = dac.Getset(sqlss);

        if (ds.Tables[0].Rows.Count == 0)
        {
            string sql = "insert into Goods_content (fgoodsid ,topstate,newstate,goodsstate,special)";
            sql += " values ('" + box.ToolTip + "','0','1','0','0')";
            a = dac.ExecuteNonQuery(sql);
        }
        else
        {
            string sqls = string.Empty;
            if (((CheckBox)sender).Checked)
            {

                sqls = " update Goods_content set newstate = '1' where fgoodsid='" + box.ToolTip + "' ";
            }
            else
            {
                sqls = " update Goods_content set newstate = '0' where fgoodsid='" + box.ToolTip + "' ";
            }
            dac.ExecuteNonQuery(sqls);
        }
    }
    /// <summary>
    /// 修改热卖状态
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void checktopid_CheckedChanged(object sender, EventArgs e)   
   {
       DAC dac = new DAC();

       int a = 0;

       CheckBox box = sender as CheckBox;
       string sqlss = "select * from Goods_content where fgoodsid = '" + box.ToolTip + "'";
       ds = dac.Getset(sqlss);

       if (ds.Tables[0].Rows.Count == 0)
        {
            string sql = "insert into Goods_content (fgoodsid ,topstate,newstate,goodsstate,special)";
            sql += " values ('" + box.ToolTip + "','1','0','0','0')";
            a = dac.ExecuteNonQuery(sql);
        }
        else
        {
            string sqls = string.Empty;
            if (((CheckBox)sender).Checked)
            {

                sqls = " update Goods_content set topstate = '1' where fgoodsid='" + box.ToolTip + "' ";

            }
            else
            {
                sqls = " update Goods_content set topstate = '0' where fgoodsid='" + box.ToolTip + "' ";
              
            }
            dac.ExecuteNonQuery(sqls);
        }
    }
    /// <summary>
    /// 修改推荐状态
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void checkgoodsid_CheckedChanged(object sender, EventArgs e)
      {
        DAC dac = new DAC();

        int a = 0;
       
        CheckBox box = sender as CheckBox;
        string sqlss = "select * from Goods_content where fgoodsid = '" + box.ToolTip + "'";  //根据商品款号来查询Goods_content 是否存在状态
        ds = dac.Getset(sqlss);

        if (ds.Tables[0].Rows.Count == 0 ) //如果Goods_content表没有相应的产品款号存在,则添加进去,如果有,就修改状态
        {
            string sql = "insert into Goods_content (fgoodsid ,topstate,newstate,goodsstate,special)";
            sql += " values ('" + box.ToolTip + "','0','0','1','0')";
            a = dac.ExecuteNonQuery(sql);
        }
        else
        {
            string sqls = string.Empty;
            if (((CheckBox)sender).Checked)
            {

                sqls = " update Goods_content set goodsstate = '1' where fgoodsid='" + box.ToolTip + "' ";

            }
            else
            {
                sqls = " update Goods_content set goodsstate = '0' where fgoodsid='" + box.ToolTip + "' ";
           
            }
            dac.ExecuteNonQuery(sqls);
        }
    }

}

 

调用到得方法在DAC

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.Data.OleDb;
//using System.Data.OracleClient;
using System.Data.Sql;
using System.Data.SqlClient;

 

public class DAC
{

    /// <summary>
    /// 取得数据库连接字符串(密文) 变量
    /// </summary>
    private string strConnectionStrTMP = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

 
    /// <summary>
    /// 取得数据库连接字符串(明文) 变量
    /// </summary>
    private string strConnectionStr = "";
    //<add name="ConnectionString" connectionString="f5e40a8ad7069982230a4557a209efcdc8406b978b83f848683119101168a95884a3d3b9ddcbfa2b827642116af3e868ea4c33868f13aa8fa2a04d2a30eb437f" providerName="System.Data.OracleClient" />

    /// <summary>
    /// 数据库连接 变量
    /// </summary>
    private SqlConnection sqlConn = null;
    /// <summary>
    /// 数据库命令 变量
    /// </summary>
    private SqlCommand sqlCmd = null;

    //-----------------------------------------------------------------------------
    /// <summary>
    /// 数据访问层操作类 构造方法
    /// </summary>
    //-----------------------------------------------------------------------------
    public DAC()
    {
        try
        {
            //解密字符串
          //strConnectionStr =  Utility.DecryptString(strConnectionStrTMP,"");
            strConnectionStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            //判断连接是否存在,如果不存在则新建一个Connection
            if (sqlConn == null)
            {
                sqlConn = new SqlConnection(strConnectionStr);
            }
        }
        catch
        {
            throw new Exception("数据库未正常连接!");
        }
    }

    #region '打开/关闭Oracle数据库连接 方法

    //-----------------------------------------------------------------------------
    /// <summary>
    ///打开Oracle数据库连接
    /// </summary>
    //-----------------------------------------------------------------------------
    public void OpenConn()
    {
        try
        {
            if (sqlConn.State == ConnectionState.Closed)
                sqlConn.Open();
            else
            {
                if (sqlConn.State == ConnectionState.Broken)
                {
                    sqlConn.Close();
                    sqlConn.Open();
                }
            }
        }
        catch (Exception )
        {
            throw;
            //throw new Exception("数据库未正常连接!");
        }
    }

    /// <summary>
    ///关闭Oracle数据库连接
    /// </summary>
    public void CloseConn()
    {
        if (sqlConn == null) return;
        if (sqlConn.State == ConnectionState.Open || sqlConn.State == ConnectionState.Broken)
        {
            sqlConn.Close();
        }
    }

    #endregion

    #region LLP
    /// <summary>
    /// Llp添加
    /// </summary>
    /// <param name="cmdText"></param>
    /// <returns></returns>
    public int ExecuteNonQuery(string cmdText)
    {
        int retVal;

        using (sqlConn = new SqlConnection(strConnectionStr))
        {
            SqlCommand cmd = new SqlCommand(cmdText, sqlConn);
            cmd.CommandType = CommandType.Text;

            sqlConn.Open();
            retVal = cmd.ExecuteNonQuery();
            sqlConn.Close();
        }

        return retVal;
    }
    /// <summary>
    /// llp添加
    /// </summary>
    /// <param name="cmdText"></param>
    /// <param name="parms"></param>
    /// <param name="cmdtype"></param>
    /// <returns></returns>
    public int ExecuteNonQuery(string cmdText, SqlParameter[] parms, CommandType cmdtype)
    {
        int retVal;
        using (sqlConn = new SqlConnection(strConnectionStr))
        {
            SqlCommand cmd = new SqlCommand(cmdText, sqlConn);
            cmd.CommandType = cmdtype;

            if (parms != null)
            {
                //添加参数
                cmd.Parameters.AddRange(parms);
            }

            sqlConn.Open();
            retVal = cmd.ExecuteNonQuery();
            sqlConn.Close();
        }

        return retVal;
    }

    /// <summary>
    ///返回DataTable _llp添加12月17日
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public DataTable GetDataSet(string sql)
    {
        sqlConn = new SqlConnection(strConnectionStr);
        sqlConn.Open();
        SqlCommand com = new SqlCommand(sql, sqlConn);
        DataSet ds = new DataSet();
        SqlDataAdapter dap = new SqlDataAdapter(com);
        dap.Fill(ds);

        return ds.Tables[0];
    }
    #endregion
    /// <summary>
    /// 返回DataSet
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public DataSet Getset(string sql)
    {
        sqlConn = new SqlConnection(strConnectionStr);
        sqlConn.Open();
        SqlCommand com = new SqlCommand(sql, sqlConn);
        DataSet ds = new DataSet();
        SqlDataAdapter dap = new SqlDataAdapter(com);
        dap.Fill(ds);

        return ds;
    }


    #region zhangting

    #region 根据sql语句获得一个DataTable
    /// <summary>
    /// 根据sql语句获得一个DataTable
    /// </summary>
    /// <param name="Sql"></param>
    /// <returns></returns>
    public DataTable ExecQuery(string Sql)
    {
        sqlConn = new SqlConnection();
        OpenConn();
        SqlDataAdapter da = new SqlDataAdapter(Sql, sqlConn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
       
    }
    #endregion

    #region 实现 增 删 改 功能,返回布尔类型
    /// <summary>
    /// 实现 增 删 改 功能,返回布尔类型
    /// </summary>
    // <param name="str"></param>
     //<returns></returns>
    public bool ExecUpDate(string str)
    {
        sqlConn = new SqlConnection();
        OpenConn();
        SqlCommand com = new SqlCommand(str, sqlConn);
        int i = com.ExecuteNonQuery();
        if (i > 0)
        {
           return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region 执行数据库,增、删、改
    /// <summary>
    /// 执行数据库,增、删、改
    /// </summary>
    /// <param name="sql">预编译的sql语句</param>
    /// <returns>影响的行数</returns>
    public int UpDate(string sql)
    {
        int num = 0;
        sqlConn = new SqlConnection();
        OpenConn();
        SqlCommand objcom = new SqlCommand(sql, sqlConn);
        num = objcom.ExecuteNonQuery();
        return num;
    }
    #endregion

    #region  根据sql语句获得单个查询结果
    /// <summary>
    /// 根据sql语句获得单个查询结果
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public string GetSingleValueFromSql(string strSql)
    {
        sqlConn = new SqlConnection();
        OpenConn();
        try
        {
            SqlCommand cmd = new SqlCommand(strSql, sqlConn);
            string result = cmd.ExecuteScalar().ToString();
            return result;
        }
        catch
        {
            return "";
        }
        finally {
            CloseConn();
        }
       
    }
    #endregion

    #region 执行事务处理SQL
    /// <summary>
    /// 执行事务处理SQL
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public bool ExecTSQL(string[] strSql) //执行事务处理SQL
    {
        sqlConn = new SqlConnection();
        OpenConn();
        SqlTransaction trans = sqlConn.BeginTransaction(IsolationLevel.ReadCommitted);
        try
        {
            for (int i = 0; i < strSql.Length; i++)
            {
                if (strSql[i] == "" || strSql[i] == null) { continue; }
                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.Transaction = trans;
                sqlCmd.CommandText = strSql[i];
                sqlCmd.ExecuteNonQuery();
            }
            trans.Commit();
            return true;
        }
        catch
        {
            trans.Rollback();
            return false;
        }
        finally
        {
            trans = null;
            CloseConn();
        }
    }
    #endregion

    #endregion

    #region '通过调用存储过程 获得DataSet 方法

    //-----------------------------------------------------------------------------
    /// <summary>
    /// 通过调用存储过程获得DataSet
    /// </summary>
    /// <param name="strProcudureName">存储过程名称</param>
    /// <param name="ds">数据集变量</param>
    /// <param name="oracleparam">存储过程需要的参数</param>
    /// <returns>数据集结果</returns>
    //-----------------------------------------------------------------------------
    public KISSError GetDSet(CommandType cmdType, string strProcudureName, ref DataSet ds, params SqlParameter[]  oracleparam)
    {
        KISSError errReturn = KISSError.KISS_OK;                                 //统一错误处理对象 初始化时标志没有错误

        try
        {
           
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = strProcudureName;
            sqlCmd.CommandType = cmdType;

            ds = new DataSet();
            if (oracleparam != null)
            {
                foreach (SqlParameter parm in oracleparam)
                    sqlCmd.Parameters.Add(parm);
            }


            SqlDataAdapter oracleAdp = new SqlDataAdapter();
            oracleAdp.SelectCommand = sqlCmd;

            oracleAdp.Fill(ds);
      
        }
        catch (Exception ex)
        {
            errReturn = new KISSError();
            errReturn.ErrorLevel = SysEnums.KISSErrorLevel.SystemError;   //系统错误
            errReturn.ModuleName = ex.GetType().FullName;
            errReturn.MethodName = ex.TargetSite.ToString();
            errReturn.UserErrMsg = ex.Message;
            //throw new Exception(ex.GetType().ToString() + ex.Message);

        }
        finally
        {
            sqlConn.Close();
        }

        return errReturn;
        //return ds;
    }

    //-----------------------------------------------------------------------------
    /// <summary>
    /// 通过调用存储过程获得DataSet
    /// </summary>
    /// <param name="strProcudureName">存储过程名称</param>
    /// <param name="oracleparam">存储过程需要的参数</param>
    /// <returns>数据集</returns>
    //-----------------------------------------------------------------------------
    public DataSet GetDSet(CommandType cmdType, string strProcudureName,params SqlParameter[] oracleparam)
    {
        DataSet ds = new DataSet();
        try
        {
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = strProcudureName;
            sqlCmd.CommandType = cmdType;      
            if (oracleparam != null)
            {
                foreach (SqlParameter parm in oracleparam)
                    sqlCmd.Parameters.Add(parm);
               
            }

            SqlDataAdapter oracleAdp = new SqlDataAdapter();
            oracleAdp.SelectCommand = sqlCmd;
            oracleAdp.Fill(ds);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.GetType().ToString() + ex.Message);
        }
        finally
        {
            sqlConn.Close();
        }

        return ds;
    }


    #endregion

    #region 获取指定的值
    //****************create by cenlo *******
    //****************time:208-05-07 ********
    /// <summary>
    /// 获取指定的值
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public string QueryValue(string strSql)
    {
        string returnValue = "";
        sqlCmd = new SqlCommand();
        sqlCmd.Connection = sqlConn;
        OpenConn();
        sqlCmd.CommandText = strSql;
        sqlCmd.CommandType = CommandType.Text;
        SqlDataReader odr = sqlCmd.ExecuteReader();     
       
        while (odr.Read())
        {
            returnValue +=  Convert.ToString(odr.GetString(0))+",";          
        }
        odr.Close();
        CloseConn();
        return returnValue.Trim(',');
    }
    #endregion

    #region 是否是用户方法
    //-----------------------------------------------------------------------------
    /// <summary>
    /// 是否是用户方法
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    //-----------------------------------------------------------------------------
    public bool isUser(string strSql)
    {
      
        sqlCmd = new SqlCommand();
        sqlCmd.Connection = sqlConn;
        OpenConn();
        sqlCmd.CommandText = strSql;
        sqlCmd.CommandType = CommandType.Text;
        SqlDataReader odr = sqlCmd.ExecuteReader();
         if(odr.Read())
        {
            return true;
        }
         odr.Close();
         CloseConn();
         return false;
    }
    //**************** end ********************
    #endregion

    #region '执行SQL(或通过调用存储过程) 4种方法

    //-----------------------------------------------------------------------------
    /// <summary>
    /// 通过调用存储过程执行SQL
    /// </summary>
    /// <param name="strProcudureName">存储过程名称</param>
    /// <param name="oracleparam">存储过程需要的参数</param>
    /// <returns>KISSError</returns>
    //-----------------------------------------------------------------------------
    public KISSError ExecSql(CommandType cmdType, string strProcudureName, params SqlParameter[] oracleparam)
    {
        KISSError errReturn = KISSError.KISS_OK;                                 //统一错误处理对象 初始化时标志没有错误

        try
        {
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = strProcudureName;
            sqlCmd.CommandType = cmdType;

            int intExecNum = -1;                                 // 被执行的记录行数 (-1:失败)

            if (oracleparam != null)
            {
                foreach (SqlParameter parm in oracleparam)
                    sqlCmd.Parameters.Add(parm);
            }


            intExecNum = sqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errReturn = new KISSError();
            errReturn.ErrorLevel = SysEnums.KISSErrorLevel.SystemError;   //系统错误
            errReturn.ModuleName = ex.GetType().FullName;
            errReturn.MethodName = ex.TargetSite.ToString();
            errReturn.UserErrMsg = ex.Message;
            //throw new Exception(ex.GetType().ToString() + ex.Message);

        }
        finally
        {
            sqlCmd.Parameters.Clear();
            sqlConn.Close();
        }

        return errReturn;
    }

    //-----------------------------------------------------------------------------
    /// <summary>
    ///  通过调用存储过程执行SQL,返回影响行数
    /// </summary>
    /// <param name="cmdType">SQL类型</param>
    /// <param name="strProcudureName">存储过程的名字</param>
    /// <param name="intExecNum">执行过存储过程所受影响的行数(使参数按引用传递,传递到 ref 参数的参数必须最先初始化)</param>
    /// <param name="oracleparam">参数数组</param>
    /// <returns>KISSError</returns>
    //-----------------------------------------------------------------------------
    public KISSError ExecSql(CommandType cmdType, string strProcudureName, ref int intExecNum, params SqlParameter[] oracleparam)
    {
        KISSError errReturn = KISSError.KISS_OK;                                 //统一错误处理对象 初始化时标志没有错误

        try
        {
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = strProcudureName;
            sqlCmd.CommandType = cmdType;

            intExecNum = -1;                                 // 被执行的记录行数 (-1:失败)

            if (oracleparam != null)
            {
                foreach (SqlParameter parm in oracleparam)
                    sqlCmd.Parameters.Add(parm);
            }


            intExecNum = sqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errReturn = new KISSError();
            errReturn.ErrorLevel = SysEnums.KISSErrorLevel.SystemError;   //系统错误
            errReturn.ModuleName = ex.GetType().FullName;
            errReturn.MethodName = ex.TargetSite.ToString();
            errReturn.UserErrMsg = ex.Message;
            //throw new Exception(ex.GetType().ToString() + ex.Message);

        }
        finally
        {
            sqlCmd.Parameters.Clear();
            sqlConn.Close();
        }

        return errReturn;
    }

    //-----------------------------------------------------------------------------
    /// <summary>
    /// 执行SQL文 方法
    /// </summary>
    /// <returns></returns>
    //-----------------------------------------------------------------------------   
    public KISSError ExecSql(string SQL)
    {
        KISSError errReturn = KISSError.KISS_OK;                                 //统一错误处理对象 初始化时标志没有错误

        try
        {
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = SQL;
            sqlCmd.CommandType = CommandType.Text;

                                            // 被执行的记录行数 (-1:失败)

             sqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errReturn = new KISSError();
            errReturn.ErrorLevel = SysEnums.KISSErrorLevel.SystemError;   //系统错误
            errReturn.ModuleName = ex.GetType().FullName;
            errReturn.MethodName = ex.TargetSite.ToString();
            errReturn.UserErrMsg = ex.Message;
            //throw new Exception(ex.GetType().ToString() + ex.Message);

        }
        finally
        {
            sqlCmd.Parameters.Clear();
            sqlConn.Close();
        }

        return errReturn;
    }


    //-----------------------------------------------------------------------------
   /// <summary>
    /// 通过调用存储过程,返回执行结果
   /// </summary>
    /// <param name="cmdType">SQL类型</param>
    /// <param name="strProcudureName">存储过程的名字</param>
   /// <param name="rtnMsg">返回提示信息</param>
    /// <param name="oracleparam">参数数组</param>
    /// <returns>errReturn</returns>
    //-----------------------------------------------------------------------------
    public KISSError GetExecResult(CommandType cmdType, string strProcudureName, ref string rtnMsg, params SqlParameter[] oracleparam)
    {
        KISSError errReturn = KISSError.KISS_OK;                                 //统一错误处理对象 初始化时标志没有错误

        try
        {
            sqlCmd = new SqlCommand();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandText = strProcudureName;
            sqlCmd.CommandType = cmdType;
            if (oracleparam != null)
            {
                foreach (SqlParameter parm in oracleparam)
                    sqlCmd.Parameters.Add(parm);
            }


            sqlCmd.ExecuteNonQuery();
            rtnMsg = sqlCmd.Parameters["returnText"].Value.ToString();
        }
        catch (Exception ex)
        {
            errReturn = new KISSError();
            errReturn.ErrorLevel = SysEnums.KISSErrorLevel.SystemError;   //系统错误
            errReturn.ModuleName = ex.GetType().FullName;
            errReturn.MethodName = ex.TargetSite.ToString();
            errReturn.UserErrMsg = ex.Message;
            //throw new Exception(ex.GetType().ToString() + ex.Message);
        }
        finally
        {
            sqlCmd.Parameters.Clear();
            sqlConn.Close();
        }

        return errReturn;
    }

    #endregion

    #region 分页
    /// <summary>
    /// 返回一个数据集
    /// </summary>
    /// <param name="sqlStr">sql语句</param>
    /// <returns></returns>
    public DataSet dataSet(string sqlStr)
    {
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        sqlCmd = new SqlCommand();
        try
        {
            //openConnection();
            sqlCmd.Connection = sqlConn;
            OpenConn();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = sqlStr;
            da.SelectCommand = sqlCmd;
            da.Fill(ds);
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
        finally
        {
            //closeConnection();
            CloseConn();
        }
        return ds;
    }
    //执行数据库查询并返回一个数据集 [当前页码,每页记录条数]
    /// <summary>
    /// 分页
    /// </summary>
    /// <param name="pageIndex">当前的页数</param>
    /// <param name="pageSize">每页显示的条数</param>
    /// <param name="sqlStr">查询语句</param>
    /// <param name="tableName">查询的结果集名(表名或者视图名)</param>
    /// <returns></returns>
    public DataSet GetCurrentPage(int pageIndex, int pageSize, string sqlStr,string tableName)
    {
        //设置导入的起始地址
        int firstPage = pageIndex * pageSize;
        //string sqlStr = "select * from outputsell order by osid desc";
        SqlCommand cmd = CreateCommand(sqlStr);
        DataSet dataset = new DataSet();
        SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
        dataAdapter.Fill(dataset, firstPage, pageSize, tableName);
        cmd.Dispose();
        CloseConn();
        dataAdapter.Dispose();
        return dataset;
    }
    //创建一个命令对象并返回该对象
    public SqlCommand CreateCommand(string sqlStr)
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = sqlConn;
        OpenConn();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = sqlStr;
       
        return cmd;
    }
    #endregion
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值