C\#에서 사용 가능 한 클래스 몇 개 공유 하기

15637 단어 C#종류
본 논문 의 사례 는 여러분 에 게 몇 가지 사용 가능 한 유형 을 소개 하 였 으 며,여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
1.SQLHelper 클래스

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

using System.Configuration;
namespace MySchool.DAL
{
 public static class SQLHelper
 {
 //               SQLHelper   
 //Execetenonquery
 // public static string Constr = "server=HAPPYPIG\\SQLMODEL;database=shooltest;uid=sa;";
 public static string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
 public static int id;
 /// <summary>
 ///   NonQuery  
 /// </summary>
 /// <param name="cmdTxt"></param>
 /// <param name="parames"></param>
 /// <returns></returns>
 public static int ExecuteNonQuery(string cmdTxt, params SqlParameter[] parames)
 {
 return ExecuteNonQuery(cmdTxt, CommandType.Text, parames);
 }
 //         ExecuteNonquery
 public static int ExecuteNonQuery(string cmdTxt, CommandType cmdtype, params SqlParameter[] parames)
 {
 //         ,    0
 if (string.IsNullOrEmpty(cmdTxt))
 {
 return 0;
 }
 using (SqlConnection con = new SqlConnection(Constr))
 {
 using (SqlCommand cmd = new SqlCommand(cmdTxt, con))
 {
  if (parames != null)
  {
  cmd.CommandType = cmdtype;
  cmd.Parameters.AddRange(parames);
  }
  con.Open();
  return cmd.ExecuteNonQuery();
 }
 }
 }
 public static SqlDataReader ExecuteDataReader(string cmdTxt, params SqlParameter[] parames)
 {
 return ExecuteDataReader(cmdTxt, CommandType.Text, parames);
 }
 //SQLDataReader      
 public static SqlDataReader ExecuteDataReader(string cmdTxt, CommandType cmdtype, params SqlParameter[] parames)
 {
 if (string.IsNullOrEmpty(cmdTxt))
 {
 return null;
 }
 SqlConnection con = new SqlConnection(Constr);

 using (SqlCommand cmd = new SqlCommand(cmdTxt, con))
 {
 cmd.CommandType = cmdtype;
 if (parames != null)
 {
  
  cmd.Parameters.AddRange(parames);
 }
 con.Open();
 // reader      。 reader       ,con      
 return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
 }

 }
 public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parames)
 {
 return ExecuteDataTable(sql, CommandType.Text, parames);
 }
 //        ,  (ExecuteDataTable)
 public static DataTable ExecuteDataTable(string sql, CommandType cmdType, params SqlParameter[] parames)
 {
 if (string.IsNullOrEmpty(sql))
 {
 return null;
 }
 DataTable dt = new DataTable();
 using (SqlDataAdapter da = new SqlDataAdapter(sql, Constr))
 {
 da.SelectCommand.CommandType = cmdType;
 if (parames != null)
 {
  da.SelectCommand.Parameters.AddRange(parames);
 }
 da.Fill(dt);
 return dt;
 }
 }
 
 /// <summary>
 /// ExecuteScalar
 /// </summary>
 /// <param name="cmdTxt">     ,SQLServer  </param>
 /// <param name="parames">     ,  0       </param>
 /// <returns></returns>
 public static object ExecuteScalar(string cmdTxt, params SqlParameter[] parames)
 {
 return ExecuteScalar(cmdTxt, CommandType.Text, parames);
 } 
 //        ExecuteScalar
 public static object ExecuteScalar(string cmdTxt, CommandType cmdtype, params SqlParameter[] parames)
 {
 if (string.IsNullOrEmpty(cmdTxt))
 {
 return null;
 }
 using (SqlConnection con = new SqlConnection(Constr))
 {
 using (SqlCommand cmd = new SqlCommand(cmdTxt, con))
 {
  cmd.CommandType = cmdtype;
  if (parames != null)
  {
  cmd.Parameters.AddRange(parames);
  }
  con.Open();
 return cmd.ExecuteScalar();
 }
 }
 
 }
 //       DBHelper (  ExeceutScalar,    ,    Int  ,     )
 public static object ExecuteScalar(string cmdTxt, CommandType cmdtype,SqlTransaction sqltran, params SqlParameter[] parames)
 {
 if (string.IsNullOrEmpty(cmdTxt))
 {
 return 0;
 }
 using (SqlConnection con = new SqlConnection(Constr))
 {
 int sum = 0;
 using (SqlCommand cmd = new SqlCommand(cmdTxt, con))
 {
  cmd.CommandType=cmdtype;
  if (parames != null)
  {
  cmd.Parameters.AddRange(parames);
  }
  con.Open();
  sqltran = con.BeginTransaction();
  try
  {
  cmd.Transaction = sqltran;
  sum=Convert.ToInt32( cmd.ExecuteScalar());
  sqltran.Commit();
  }
  catch (SqlException ex)
  {
  sqltran.Rollback();
  }
  return sum;
 }
 }
 }
 }
}

예 를 들 면:

 //            
 public DataTable LoadCombox()
 {
 string sql = "select * from Grade";
 DataTable dt = SQLHelper.ExecuteDataTable(sql);
 return dt;
 }
2.MyTool 클래스(DataTable 변환 목록<>)

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MySchool.DAL
{
 public class MyTool
 {
 /// <summary>
 /// DataSetToList
 /// </summary>
 /// <typeparam name="T">    </typeparam>
 /// <param name="dataSet">   </param>
 /// <param name="tableIndex">        </param>
 /// <returns></returns>
 public List<T> DataTableToList<T>(DataTable dt)
 {
 //      
 if (dt == null )
 return null;
 List<T> list = new List<T>();

 for (int i = 0; i < dt.Rows.Count; i++)
 {
 //      
 T _t = Activator.CreateInstance<T>();
 //        
 PropertyInfo[] propertyInfo = _t.GetType().GetProperties();
 for (int j = 0; j < dt.Columns.Count; j++)
 {
  foreach (PropertyInfo info in propertyInfo)
  {
  //            
  if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
  {
  if (dt.Rows[i][j] != DBNull.Value)
  {
  info.SetValue(_t, dt.Rows[i][j], null);
  }
  else
  {
  info.SetValue(_t, null, null);
  }
  break;
  }
  }
 }
 list.Add(_t);
 }
 return list;
 }
 }
}
예 를 들 면: 

 public List<Grade> Loadcombox2() 
 {
 string sql = "select * from Grade";
 DataTable dt = SQLHelper.ExecuteDataTable(sql);
 //   :
 foreach (DataRow row in dt.Rows)
 {
  //   row       ,            
  Grade grade = new Grade();
  grade.GradeId = Convert.ToInt32(row["gradeid"]);
  grade.GradeName = row["gradename"].ToString();
  list.Add(grade);
 }

 //   :(  MyTool )
 MyTool tool=new MyTool();
 list = tool.DataTableToList<Grade>(dt);
 return list;
 }

3.DGMsgDiv 클래스(자신의 컨트롤 생 성 가능) 

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

/// <summary>
///          
/// </summary>
public delegate void DGMsgDiv();
 /// <summary>
 ///       Timer  
 /// </summary>
public class MsgDiv : System.Windows.Forms.Label
{
 private Timer timerLable = new Timer();
 /// <summary>
 ///          
 /// </summary>
 private DGMsgDiv dgCallBack = null;

 #region    
 /// <summary>
 ///    
 /// </summary>
 public Timer TimerMsg
 {
 get { return timerLable; }
 set { timerLable = value; }
 } 
 #endregion

 #region MsgDiv    
 /// <summary>
 /// MsgDiv    
 /// </summary>
 public MsgDiv()
 {
 InitallMsgDiv(7, 7);
 }

 /// <summary>
 /// MsgDiv    
 /// </summary>
 /// <param name="x">  x   </param>
 /// <param name="y">  y   </param>
 public MsgDiv(int x, int y)
 {
 InitallMsgDiv(x, y);
 }
 #endregion

 #region       
 /// <summary>
 ///       
 /// </summary>
 private void InitallMsgDiv(int x, int y)
 {
 this.AutoSize = true;
 this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
 this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
 //this.ContextMenuStrip = this.cmsList;
 this.Font = new System.Drawing.Font("  ", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
 this.ForeColor = System.Drawing.Color.Red;
 this.Location = new System.Drawing.Point(x, y);
 this.MaximumSize = new System.Drawing.Size(980, 525);
 this.Name = "msgDIV";
 this.Padding = new System.Windows.Forms.Padding(7);
 this.Size = new System.Drawing.Size(71, 31);
 this.TabIndex = 1;
 this.Text = "   ";
 this.Visible = false;
 //       
 this.DoubleClick += new System.EventHandler(this.msgDIV_DoubleClick);
 this.MouseLeave += new System.EventHandler(this.msgDIV_MouseLeave);
 this.MouseHover += new System.EventHandler(this.msgDIV_MouseHover);
 this.timerLable.Interval = 1000;
 this.timerLable.Tick += new System.EventHandler(this.timerLable_Tick);
 }
 #endregion

 #region             
 /// <summary>
 ///             Form
 /// </summary>
 /// <param name="form"></param>
 public void AddToControl(Form form)
 {
 form.Controls.Add(this);
 }
 /// <summary>
 ///             GroupBox
 /// </summary>
 /// <param name="form"></param>
 public void AddToControl(GroupBox groupBox)
 {
 groupBox.Controls.Add(this);
 }
 /// <summary>
 ///             Panel
 /// </summary>
 /// <param name="form"></param>
 public void AddToControl(Panel panel)
 {
 panel.Controls.Add(this);
 }
 #endregion

 //---------------------------------------------------------------------------
 #region             hiddenClick,countNumber,constCountNumber
 /// <summary>
 ///            
 /// </summary>
 int hiddenClick = 0;
 /// <summary>
 ///               
 /// </summary>
 int countNumber = 3;
 /// <summary>
 ///               
 /// </summary>
 int constCountNumber = 3; 
 #endregion

 #region       countNumber       div -timerLable_Tick(object sender, EventArgs e)
 private void timerLable_Tick(object sender, EventArgs e)
 {
 if (hiddenClick > countNumber - 2)
 {
 MsgDivHidden();
 }
 else
 {
 hiddenClick++;
 //RemainCount();
 }
 } 
 #endregion

 #region             +void MsgDivHidden()
 /// <summary>
 ///            
 /// </summary>
 public void MsgDivHidden()
 {
 this.Text = "";
 this.Visible = false;
 this.hiddenClick = 0;
 //this.tslblRemainSecond.Text = "";
 if (this.timerLable.Enabled == true)
 this.timerLable.Stop();

 //            
 if (dgCallBack != null && dgCallBack.GetInvocationList().Length > 0)
 {
 dgCallBack();
 dgCallBack -= dgCallBack;
 }
 } 
 #endregion

 #region              +void MsgDivShow(string msg)
 /// <summary>
 ///             
 /// </summary>
 /// <param name="msg">       </param>
 public void MsgDivShow(string msg)
 {
 this.Text = msg;
 this.Visible = true;
 this.countNumber = constCountNumber;//         10;
 this.hiddenClick = 0;//      
 this.timerLable.Start();
 } 
 #endregion

 #region                             +void MsgDivShow(string msg, DGMsgDiv callback)
 /// <summary>
 ///                            
 /// </summary>
 /// <param name="msg">       </param>
 /// <param name="callback">    </param>
 public void MsgDivShow(string msg, DGMsgDiv callback)
 {
 MsgDivShow(msg);
 dgCallBack = callback;
 }
 #endregion

 #region                                 +void MsgDivShow(string msg, int seconds, DGMsgDiv callback)
 /// <summary>
 ///                            
 /// </summary>
 /// <param name="msg">       </param>
 /// <param name="seconds">      </param>
 /// <param name="callback">    </param>
 public void MsgDivShow(string msg, int seconds, DGMsgDiv callback)
 {
 MsgDivShow(msg, seconds);
 dgCallBack = callback;
 } 
 #endregion

 #region             ,           +void MsgDivShow(string msg, int seconds)
 /// <summary>
 ///             ,          
 /// </summary>
 /// <param name="msg">       </param>
 /// <param name="seconds">       </param>
 public void MsgDivShow(string msg, int seconds)
 {
 this.Text = msg;
 this.Visible = true;
 this.countNumber = seconds;
 this.hiddenClick = 0;//      
 this.timerLable.Start();
 } 
 #endregion

 //---------------------------------------------------------------------------
 #region    ~~~! msgDIV_MouseHover,msgDIV_MouseLeave,msgDIV_DoubleClick
 //      div       
 private void msgDIV_MouseHover(object sender, EventArgs e)
 {
 if (this.timerLable.Enabled == true)
 this.timerLable.Stop();
 }
 //    div         
 private void msgDIV_MouseLeave(object sender, EventArgs e)
 {
 //        、      、         ,       
 if (this.Visible == true && this.timerLable.Enabled == false)
 this.timerLable.Start();
 }
 //           
 private void msgDIV_DoubleClick(object sender, EventArgs e)
 {
 MsgDivHidden();
 } 
 #endregion

}
예 를 들 면:

 private void Form1_Load(object sender, EventArgs e)
 {
 //    “  ”,3     Test       “  ”
 msgDiv1.MsgDivShow("  ",3,Test);
 }

 public void Test()
 {
 MessageBox.Show("  ");
 }

이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기