工作中经常用到的C#编程小技巧

1.关于C#控件获得焦点问题
private void Form1_Activated(object sender, EventArgs e)
{
    this.textBox2.Focus();
}


若写在private void Form1_Load(object sender, EventArgs e)中
则focus总是会落到TabIndex最小的控件上。




--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
2.鼠标点击TREEVIEW的其他空白处,取消选中当前节点
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            TreeNode _Node = treeView1.GetNodeAt(e.Location);


            //if (_Node == null || !_Node.Bounds.Contains(e.Location))
            if (_Node == null)
            {
                treeView1.SelectedNode = null;
                treeView1.Refresh();


            } 
        }


----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
3.当程序在listview自动增加条目时,当内容超出一页,怎样使scrollbar自动滚动到最后一条
        private void button4_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.Text = "asasdsa";
            this.listView1.Items.Add(lvi);


            for (int i = 0; i < listView1.Items.Count; i++)
            {
                this.listView1.Items[i].Selected = false;
            }
            int index = listView1.Items.Count;
            this.listView1.Focus();
            this.listView1.Items[index - 1].Selected = true;


            listView1.Items[listView1.Items.Count - 1].EnsureVisible();
        }


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
4.左键单击NotifyIcon图标时弹出菜单
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        contextMenuStrip1.Show(Cursor.Position);
    }
}


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
5.数据库操作时用Trim()去掉取到的值的前后空格
ds.Tables["UsersInfo"].Rows[0]["Level"].ToString().Trim();


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
6.数据库查询中的where子句
string str = "select * from UsersInfo where UserId = '" + this.textUser.Text + "'"
                    + "and Password = '" + this.textPassword.Text + "'";


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
7.怎样判断文件夹下是否存在一个已知的文件
FileInfo f = new FileInfo("文件路径+文件名");   
if (f.Exists == true)
{}


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
8.隐藏标题栏
this.FormBorderStyle = FormBorderStyle.None;


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
9.任务栏不显示
this.ShowInTaskbar = false;


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
10.datetimepicker怎么显示时间
this.dateTimePicker1.CustomFormat = DateTime.Now.ToString ();
this.dateTimePicker1.Format = DateTimePickerFormat.Custom;


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
11.取消DataGridView的默认选中Cell使其不反蓝 
this.dataGridView1.Rows[0].Selected = false; 

this.dataGridView1.ClearSelection(); 
同时需要注意dataGridView1的TabIndex


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
12.鼠标移动到panel上时显示提示
private void panel1_MouseMove(object sender, MouseEventArgs e) 

    toolTip1.SetToolTip(panel1, "tooltip text"); 
}


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
13.获取当前的工作目录的路径
Environment.CurrentDirectory


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
14.如何在TextBox中输入完后按回车键时触发另一个Button的事件?
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
      if (e.KeyChar == 13)
      {      
          button1.PerformClick(); 
      }
}


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
15.
获取或设置绑定到ds数据源的控件指向的表Products的行数
this.BindingContext[ds, "Products"].Count


获取或设置绑定到ds数据源的控件指向的表Products的位置
this.BindingContext[ds, "Products"].Position


将textBox控件绑定到 dataSet1 数据集中 Customers 表的 FirstName 列:
textBox1.DataBindings.Add("Text", dataSet1, "Customers.FirstName");


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
16.数据库连接,遍历一台数据库服务器上所有的SQL数据库
string connectString = "Server=(local);Integrated Security=True;Database=master";
string connectString = "Data Source = 192.168.0.206; Initial Catalog = master; User ID = dfmc; password = 123456;";


select * from master.dbo.sysdatabases


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
17.获取局域网内的所有数据库服务器名称
        public List GetSqlServerNames()
        {
            DataTable dataSources = SqlClientFactory.Instance.CreateDataSourceEnumerator().GetDataSources();


            DataColumn column = dataSources.Columns["InstanceName"];
            DataColumn column2 = dataSources.Columns["ServerName"];


            DataRowCollection rows = dataSources.Rows;
            List Serverlist = new List();
            string array = string.Empty;
            for (int i = 0; i < rows.Count; i++)
            {
                string str2 = rows[i][column2] as string;
                string str = rows[i][column] as string;
                if (((str == null) || (str.Length == 0)) || ("MSSQLSERVER" == str))
                {
                    array = str2;
                }
                else
                {
                    array = str2 + @"\" + str;
                }


                Serverlist.Add(array);
            }


            Serverlist.Sort();


            return Serverlist;
        }


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
18.从app.config中读取连接字符串


App.config文件为:


 
          name ="QQ"
      providerName="System.Data.SqlClient"
      connectionString ="Server=(local);Integrated Security=True;Database=QQ"
    />
 




程序中为:
添加using System.Configuration;和引用System.Configuration


string str = ConfigurationManager.ConnectionStrings["QQ"].ToString();

ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["QQ"];
if (settings != null)
{
    Console.WriteLine(settings.ConnectionString);
}


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
19.递归添加treeview节点


数据库结构:   
  id            name              parentid 
  1             一级                 0 
  2             科技                 1 
  3             沈阳                 2 
  4             二级                 0 
  5             美食                 4 
  6             哈尔滨               5 
  7             三级                 0 
  8             美食                 7 
  9             大连                 8


       private   void   LoadTree() 
       {
            treeView1.Nodes.Clear();     //先清空树 
            DataTable dt = ds.Tables[0]; //把表结构从数据库查出来放到DataTable中 
            //循环绑定父节点 
            foreach (DataRow dr in dt.Rows)
            {
                //遍历加载父节点 
                if (Convert.ToInt32(dr["parentid"]) == 0)
                {
                    TreeNode newNode = new TreeNode(dr["name"].ToString());
                    treeView1.Nodes.Add(newNode);


                    ChildLoad(dr, newNode, dt);
                }                 
            }


            this.treeView1.ExpandAll();
        }


        //绑定子节点 
        private void ChildLoad(DataRow dr, TreeNode newNode, DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToInt32(dr["id"]) == Convert.ToInt32(row["parentid"]))
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = row["name"].ToString();
                    newNode.Nodes.Add(childNode);


                    ChildLoad(row, childNode, dt);   //递归子节点 
                }
            }
        }


-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


20.使dataGridView选中行随着鼠标指针的移动而跟随


   将属性SelectionMode设为FullRowSelect
   将属性MultiSelect设为false
        private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > 0)
            {
                this.dataGridView1.Rows[e.RowIndex].Selected = true;
            }
        }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


21.linq分组查询


Title      Module          Language          Num 
A1          software1        French            1 
A2          software1        French            2 
A1          software1        German            3 
A2          software1        German            4 
A1          software2        French            5 
A2          software2        French            6 
A1          software2        German            7 
A2          software2        German            8 


按Title和Module分组,结果如下表: 
Title      Module          sum_num      
A1          software1      1+3=4              
A2          software1      2+4=6 
A1          software2      5+7=12              
A2          software2      6+8=14


var result = from t in table.AsEnumerable() 
            group t by new { g1 = t.Field ("Title"), g2 = t.Field ("Module") } 
            into t2 
            select new 
            { 
                  Title = t2.Key.g1, 
                  Module = t2.Key.g2, 
                  Sum_Num = t2.Sum(u => u.Field ("Num")) 
                  或
                  Sum_Num = (from r1 in t2 select r1.Field ("Num")).Sum()
            }; 
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


22.Linq to Sql中添加,修改,删除操作
  DataClasses1DataContext db = new DataClasses1DataContext();


  Customer newCust = new Customer();
  newCust.CompanyName = "1";
  newCust.CustomerID = "1";


  db.Customers.InsertOnSubmit(newCust);
  db.SubmitChanges();
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


23.获取计算机当前用户
  System.Environment.UserName
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


24.窗体上就放一个button和一个label,点击button后处理后台数据,然后在label上显示“loading...”,
   数据处理完毕之后label显示“完成”。


private delegate void TestDelegate(string s);


        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Loading...";
            Thread thd = new Thread(st);   //st是线线程调用的方法,也就是你处理数据的方法
            thd.Start();
        }


        private void st()
        {
            Thread.Sleep(2000); //为了测试,线程停2秒,当然可以在这之前写你处理数据的代码


            //因为线程里面不能访问控件,所以用Invoke调用ThreadEndCallback方法
            TestDelegate myDelegate = new TestDelegate(ThreadEndCallback);
            this.Invoke(myDelegate, "Loading完毕!"); 
        }


        private void ThreadEndCallback(string str) //线程回调方法
        {
            label1.Text = str;
        }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


25.日期时间格式化
   
   其中月份和小时都要大写。
   string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


26.获取服务器的时间
        public string GetServerTime()
        {
            DateTime now;


            string connectString = "Data Source = 192.168.0.206; Initial Catalog = master; User ID = sa; password = 123456;";
            //string connectString = "Server=192.168.0.206;Integrated Security=True;Database=master";
            SqlConnection con = new SqlConnection(connectString);
            con.Open();


            SqlCommand command = new SqlCommand("select getdate() as systemtimes", con);
            now = (DateTime)command.ExecuteScalar();
            con.Close();


            return now.ToString ("yyyy-MM-dd HH:mm:ss");
        }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


27.winform背景音乐
    public partial class Form1 : Form
    {
        public static uint SND_ASYNC = 0x0001;  // play asynchronously 
        public static uint SND_FILENAME = 0x00020000; // name is file name


        [DllImport("winmm.dll")]
        public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback);


        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            string file = Environment.CurrentDirectory + "\\smzy_mp3_200710251010257.mp3";
            PlayMusic(file);
        }


        public static void PlayMusic(string fileName)
        {
            mciSendString(@"close temp_alias", null, 0, 0);
            mciSendString("open \"" + fileName + "\" alias temp_alias", null, 0, 0);
            mciSendString("play temp_alias repeat", null, 0, 0);
        }
    }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


28.MD5


添加using System.Security.Cryptography;


        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public static string GetMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();


            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));


            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();


            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }


            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


29.tabcontrol中某一个tabpages的隐藏与显示
   隐藏:
   this.tabControl1.TabPages.Remove(this.tabPage2);
   显示
   this.tabControl1.TabPages.Add(this.tabPage2);


   如果把tabPage2设置成置于最前:
   this.tabControl1.SelectedTab = this.tabPage2;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


30.datagridview禁止列排序
   for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
   {
        this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
   }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


31.Label改变文字大小和颜色
  this.label1.ForeColor = Color.Blue;
  this.label1.Font = new Font("SimSun", 20);
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


32.左边treeview,点击treeview节点,实现右边的界面的切换


  private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
  {
  if (e.Node.Name == "")
  {
// 假定左边panel1,右边panel2
  this.panel2.Controls.Clear();
  Form1 f= new Form1 ();
  f.TopLevel = false;
  f.FormBorderStyle = FormBorderStyle.None;
  f.WindowState = FormWindowState.Maximized;
  panel2.Controls.Add(f);
  f.Show();
  }
  }
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------


33.winform的生命周期


1.Form构造函数 InitializeComponent()
2.Form上面每个control的构造函数
3.Form_OnLoad()方法
4.Form_Load()方法
5.WndProc()传递消息方法
6.Shown()显示
7.Activated()激活





































































































你可能感兴趣的:(c#,其他)