分享

C#开发和使用中的33个技巧 - 51CTO.COM

 大卷风 2010-10-04
    本文总结了C#在开发和使用中的23个技巧,希望对大家有所帮助。

    笔者在实践过程中,总结了C#开发和使用的若干技巧,如下:
    1.怎样定制VC#DataGrid列标题?

            
    1. DataGridTableStyle dgts = new DataGridTableStyle();  
    2.  
    3. dgts.MappingName = "myTable"//myTable为要载入数据的DataTable  
    4.  
    5. DataGridTextBoxColumn dgcs = new DataGridTextBoxColumn();  
    6.  
    7. dgcs.MappingName = "title_id";  
    8.  
    9. dgcs.HeaderText = "标题ID";  
    10.  
    11. dgts.GridColumnStyles.Add(dgcs);  
    12.  
    13. ……  
    14.  
    15. dataGrid1.TableStyles.Add(dgts);  

    2.检索某个字段为空的所有记录的条件语句怎么写?

    ...where col_name is null

    3.如何在c# Winform应用中接收回车键输入?

    设一下form的AcceptButton.

    4.比如Oracle中的NUMBER(15),在Sql Server中应是什么?

    NUMBER(15):用numeric,精度15试试。

    5.sql server的应用like语句的存储过程怎样写?

            
    1. select * from mytable where haoma like ‘%’ + @hao + ‘%’ 

    6.vc# winform中如何让textBox接受回车键消息(假没没有按钮的情况下)?

            
    1. private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)  
    2.  
    3.       {  
    4.  
    5.  if(e.KeyChar != (char)13)  
    6.  
    7.  return;  
    8.  
    9.  else 
    10.  
    11.  //do something;  
    12.  
    13.  }  

    7.为什么(Int32)cmd.ExecuteScalar()赋值给Int32变量时提示转换无效?

    Int32.Parse(cmd.ExecuteScalar().ToString());

    8.DataSource为子表的DataGrid里怎样增加一个列以显示母表中的某个字段?

    在子表里手动添加一个列。 

            
    1. DataColumn dc = new DataColumn("newCol", Type.GetType("System.String"));  
    2.  
    3.  dc.Expression = "Parent.parentColumnName";  
    4.  
    5.  dt.Columns.Add(dc); //dt为子表  

    9.怎样使DataGrid显示DataTable中某列的数据时只显示某一部分?

    select ..., SUBSTR(string, start_index, end_index) as ***, *** from ***

    10.如何让winform的combobox只能选不能输入?

    DropDownStyle 属性确定用户能否在文本部分中输入新值以及列表部分是否总显示。

    值:

    DropDown --- 文本部分可编辑。用户必须单击箭头按钮来显示列表部分。

    DropDownList --- 用户不能直接编辑文本部分。用户必须单击箭头按钮来显示列表部分。

    11.怎样使winform的DataGrid里显示的日期只显示年月日部分,去掉时间?

    sql语句里加上to_date(日期字段,'yyyy-mm-dd')

    12.怎样把数据库表的二个列合并成一个列Fill进DataSet里?

    dcChehao = new DataColumn("newColumnName", typeof(string));

    dcChehao.Expression = "columnName1+columnName2";

    dt.Columns.Add(dcChehao);

    Oracle:

    select col1col2 from table

    sql server:

    select col1+col2 from table

    13.如何从合并后的字段里提取出括号内的文字作为DataGrid或其它绑定控件的显示内容?即把合并后的字段内容里的左括号(和右括号)之间的文字提取出来。

    Select COL1,COL2, case

    when COL3 like ‘%(%’ THEN substr(COL3, INSTR(COL3, ‘(’ )+1, INSTR(COL3,‘)’)-INSTR(COL3,‘(’)-1)

    end as COL3

    from MY_TABLE

    14.当用鼠标滚轮浏览DataGrid数据超过一定范围DataGrid会失去焦点。怎样解决?

            
    1. this.dataGrid1.MouseWheel+=new MouseEventHandler(dataGrid1_MouseWheel);  
    2.  
    3.  private void dataGrid1_MouseWheel(object sender, MouseEventArgs e)  
    4.  
    5. {  
    6.  
    7. this.dataGrid1.Select();  
    8.  
    9. }  

    15.怎样把键盘输入的‘+’符号变成‘A’?

    textBox的KeyPress事件中

            
    1. if(e.KeyChar == '+')  
    2.  
    3. {  
    4.  
    5. SendKeys.Send("A");  
    6.  
    7. e.Handled = true;  
    8.  
    9. }  

    16.怎样使Winform启动时直接最大化?

    this.WindowState = FormWindowState.Maximized;

    17.c#怎样获取当前日期及时间,在sql语句里又是什么?

    c#: DateTime.Now

    sql server: GetDate()

    18.怎样访问winform DataGrid的某一行某一列,或每一行每一列?

    dataGrid[row,col]

    19.怎样为DataTable进行汇总,比如DataTable的某列值‘延吉'的列为多少?

    dt.Select("城市='延吉'").Length;

    20.DataGrid数据导出到Excel后0212等会变成212。怎样使它导出后继续显示为0212?

    range.NumberFormat = "0000";

    21.① 怎样把DataGrid的数据导出到Excel以供打印?

    ② 之前已经为DataGrid设置了TableStyle,即自定义了列标题和要显示的列,如果想以自定义的视图导出数据该怎么办?

    ③ 把数据导出到Excel后,怎样为它设置边框啊?

    ④ 怎样使从DataGrid导出到Excel的某个列居中对齐?

    ⑤ 数据从DataGrid导出到Excel后,怎样使标题行在打印时出现在每一页?

    ⑥ DataGrid数据导出到Excel后打印时每一页显示’当前页/共几页’,怎样实现?

     

            
    1. private void button1_Click(object sender, System.EventArgs e)  
    2.  
    3.  {  
    4.  
    5.  int row_index, col_index;  
    6.  
    7.  row_index = 1;  
    8.  
    9.  col_index = 1;  
    10.  
    11.  Excel.ApplicationClass excel = new Excel.ApplicationClass();  
    12.  
    13.  excel.Workbooks.Add(true);  
    14.  
    15.  DataTable dt = ds.Tables["table"];  
    16.  
    17.  foreach(DataColumn dcHeader in dt.Columns)  
    18.  
    19.  excel.Cells[row_index, col_index++] = dcHeader.ColumnName;  
    20.  
    21.  foreach(DataRow dr in dt.Rows)  
    22.  
    23.  {  
    24.  
    25.  col_index = 0;  
    26.  
    27.  foreach(DataColumn dc in dt.Columns)  
    28.  
    29.  {  
    30.  
    31.  excel.Cells[row_index+1, col_index+1] = dr[dc];  
    32.  
    33.  col_index++;  
    34.  
    35.  }  
    36.  
    37.  row_index++;  
    38.  
    39.  }  
    40.  
    41.  excel.Visible = true;  
    42.  
    43.  }  
    44.  
    45.   private void Form1_Load(object sender, System.EventArgs e)  
    46.  
    47.  {  
    48.  
    49.  SqlConnection conn = new SqlConnection("server=tao; uid=sa; pwd=; database=pubs");  
    50.  
    51.  conn.Open();  
    52.  
    53.  SqlDataAdapter da = new SqlDataAdapter("select * from authors", conn);  
    54.  
    55.  ds = new DataSet();  
    56.  
    57.  da.Fill(ds, "table");  
    58.  
    59.  dataGrid1.DataSource = ds;  
    60.  
    61.  dataGrid1.DataMember = "table";  
    62.  
    63.  }  
    64.  

    ②dataGrid1.TableStyles[0].GridColumnStyles[index].HeaderText; //index可以从0~dataGrid1.TableStyles[0].GridColumnStyles.Count遍历。

    ③ Excel.Range range;

    range=worksheet.get_Range(worksheet.Cells[1,1],xSt.Cells[ds.Tables[0].Rows.Count+1,ds.Tables[0].Columns.Count]);

    range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);

        range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;

    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;

    range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;

    range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;

    range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;

    range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

    ④ range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter

    ⑤ worksheet.PageSetup.PrintTitleRows = "$1:$1";

    ⑥ worksheet.PageSetup.CenterFooter = "第&P页 / 共&N页";

    22.当把DataGrid的Cell内容赋值到Excel的过程中想在DataGrid的CaptionText上显示进度,但不显示。WHY?

    ...

    dataGrid1.CaptionText = "正在导出:" + (row + 1) + "/" + row_cnt;

    System.Windows.Forms.Application.DoEvents();

    ...

    处理当前在消息队列中的所有Windows消息。

    当运行Windows窗体时,它将创建新窗体,然后该窗体等待处理事件。该窗体在每次处理事件时,均将处理与该事件关联的所有代码。所有其他事件在队列中等待。在代码处理事件时,应用程序并不响应。如果在代码中调用DoEvents,则应用程序可以处理其他事件。

    如果从代码中移除DoEvents,那么在按钮的单机事件处理程序执行结束以前,窗体不会重新绘制。通常在循环中使用该方法来处理消息。

    23.怎样从Flash调用外部程序,如一个C#编译后生成的.exe?

    fscommand("exec", "应用程序.exe");

    ① 必须把flash发布为.exe

    ② 必须在flash生成的.exe文件所在目录建一个名为fscommand的子目录,并把要调用的可执行程序拷贝到那里。

    24.有没有办法用代码控制DataGrid的上下、左右的滚动?

            
    1. dataGrid1.Select();  
    2.  
    3. SendKeys.Send("{PGUP}");  
    4.  
    5. SendKeys.Send("{PGDN}");  
    6.  
    7. SendKeys.Send("{^{LEFT}"); // Ctrl+左方向键  
    8.  
    9. SendKeys.Send("{^{RIGHT}"); // Ctrl+右方向键  

    25.怎样使两个DataGrid绑定两个主从关系的表?

            
    1. DataGrid1.DataSource = ds;  
    2.  
    3. DataGrid1.DataMember = "母表";  
    4.  
    5. ...  
    6.  
    7. DataGrid2.DataSouce = ds;  
    8.  
    9. DataGrid2.DataMember = "母表.关系名";  

    26.assembly的版本号怎样才能自动生成?特别是在Console下没有通过VStudio环境编写程序时。

    关键是AssemblyInfo.cs里的[assembly: AssemblyVersion("1.0.*")],命令行编译时包含AssemblyInfo.cs

    27.怎样建立一个Shared Assembly?

    用sn.exe生成一个Strong Name:keyfile.sn,放在源程序目录下

    在项目的AssemblyInfo.cs里[assembly: AssemblyKeyFile("..\\..\\keyfile.sn")]

    生成dll后,用gacutil /i myDll.dll放进Global Assembly Cach.

    28.在Oracle里如何取得某字段第一个字母为大写英文A~Z之间的记录?

    select * from table where ascii(substr(字段,1,1)) between ascii('A') and ascii('Z')

    29.怎样取得当前Assembly的版本号?

            
    1. Process current = Process.GetCurrentProcess();  
    2.  
    3. FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(current.MainModule.FileName);  
    4.  
    5. Console.WriteLine(myFileVersionInfo.FileVersion);  

    30.怎样制作一个简单的winform安装程序?

    ① 建一个WinForm应用程序,最最简单的那种。运行。

    ② 添加新项目->安装和部署项目,‘模板’选择‘安装向导’。

    ③ 连续二个‘下一步’,在‘选择包括的项目输出’步骤打勾‘主输出来自’,连续两个‘下一步’,‘完成’。

    ④ 生成。

    ⑤ 到项目目录下找到Setup.exe(还有一个.msi和.ini文件),执行。

    31.怎样通过winform安装程序在Sql Server数据库上建表?

    ① [项目]—[添加新项]

    类别:代码;模板:安装程序类。

    名称:MyInstaller.cs

    ② 在SQL Server建立一个表,再[所有任务]—[生成SQL脚本]。

    生成类似如下脚本(注意:把所有GO语句去掉):

            
    1.  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]'and OBJECTPROPERTY(id, N'IsUserTable') = 1)  
    2.  
    3. drop table [dbo].[MyTable]  
    4.  
    5. CREATE TABLE [dbo].[MyTable] (  
    6.  
    7. [ID] [intNOT NULL ,  
    8.  
    9. [NAME] [nchar] (4) COLLATE Chinese_PRC_CI_AS NOT NULL 
    10.  
    11. ON [PRIMARY]  
    12.  
    13. ALTER TABLE [dbo].[MyTable] WITH NOCHECK ADD 
    14.  
    15. CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED  
    16.  
    17. (  
    18.  
    19. [ID]  
    20.  
    21. ON [PRIMARY]  

    ③ [项目]—[添加现有项]。mytable.sql—[生成操作]-[嵌入的资源]。

    ④ 将MyInstaller.cs切换到代码视图,添加下列代码:

    先增加:

            
    1. using System.Reflection;  
    2.  
    3.  using System.IO;  

    然后:

     

            
    1. private string GetSql(string Name)  
    2.  
    3.  {  
    4.  
    5.  try 
    6.  
    7.  {  
    8.  
    9.   Assembly Asm = Assembly.GetExecutingAssembly();  
    10.  
    11.  Stream strm = Asm.GetManifestResourceStream(Asm.GetN  
    12.  
    13.  ame().Name + "." + Name);  
    14.  
    15.  StreamReader reader = new StreamReader(strm);  
    16.  
    17.  return reader.ReadToEnd();  
    18.  
    19.  }  
    20.  
    21.  catch (Exception ex)  
    22.  
    23.  {  
    24.  
    25.  Console.Write("In GetSql:"+ex.Message);  
    26.  
    27.  throw ex;  
    28.  
    29.  }  
    30.  
    31.  }  
    32.  
    33.  private void ExecuteSql(string DataBaseName,string Sql)  
    34.  
    35.  {  
    36.  
    37.  System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();  
    38.  
    39.  sqlConn.ConnectionString = "server=myserver; uid=sa; password=; database=master";  
    40.  
    41.  System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql,sqlConn);  
    42.  
    43.  Command.Connection.Open();  
    44.  
    45. Command.Connection.ChangeDatabase(DataBaseName);  
    46.  
    47.  try 
    48.  
    49.  {  
    50.  
    51.  Command.ExecuteNonQuery();  
    52.  
    53.  }  
    54.  
    55.  finally 
    56.  
    57.  {  
    58.  
    59.  Command.Connection.Close();  
    60.  
    61.  }  
    62.  
    63.  }  
    64.  
    65.  protected void AddDBTable(string strDBName)  
    66.  
    67.  {  
    68.  
    69.  try 
    70.  
    71.  {  
    72.  
    73.  ExecuteSql("master","create DATABASE "+ strDBName);  
    74.  
    75.  ExecuteSql(strDBName,GetSql("mytable.sql"));  
    76.  
    77.  }  
    78.  
    79.  catch(Exception ex)  
    80.  
    81.  {  
    82.  
    83.  Console.Write("In exception handler :"+ex.Message);  
    84.  
    85.  }  
    86.  
    87.  }  
    88.  
    89.  public override void Install(System.Collections.IDictionary stateSaver)  
    90.  
    91.  {  
    92.  
    93.  base.Install(stateSaver);  
    94.  
    95.  AddDBTable("MyDB"); //建一个名为MyDB的DataBase  
    96.  
    97.  }  

    ⑤ [添加新项目]—[项目类型:安装和部署项目]—[模板:安装项目]—[名称:MySetup]。

    ⑥ [应用程序文件夹]—[添加]—[项目输出]—[主输出]。

    ⑦ 解决方案资源管理器—右键—[安装项目(MySetup)]—[视图]—[自定义操作]。[安装]—[添加自定义操作]—[双击:应用程序文件夹]的[主输出来自***(活动)]。

    32.怎样用TreeView显示父子关系的数据库表(winform)?

    三个表a1,a2,a3, a1为a2看母表,a2为a3的母表。

    a1: id, name

    a2: id, parent_id, name

    a3: id, parent_id, name

    用三个DataAdapter把三个表各自Fill进DataSet的三个表。

    用DataRelation设置好三个表之间的关系。

            
    1. foreach(DataRow drA1 in ds.Tables["a1"].Rows)  
    2.  
    3. {  
    4.  
    5. tn1 = new TreeNode(drA1["name"].ToString());  
    6.  
    7. treeView1.Nodes.Add(tn1);  
    8.  
    9. foreach(DataRow drA2 in drA1.GetChildRows("a1a2"))  
    10.  
    11. {  
    12.  
    13. tn2 = new TreeNode(drA2["name"].ToString());  
    14.  
    15.  tn1.Nodes.Add(tn2);  
    16.  
    17.  foreach(DataRow drA3 in drA2.GetChildRows("a2a3"))  
    18.  
    19.  {  
    20.  
    21.   tn3 = new TreeNode(drA3["name"].ToString());  
    22.  
    23.  tn2.Nodes.Add(tn3);  
    24.  
    25.  }  
    26.  
    27.   }  
    28.  
    29.  }  

    33.怎样从一个form传递数据到另一个form?

    假设Form2的数据要传到Form1的TextBox。

    在Form2:

     

            
    1. // Define delegate  
    2.  
    3.    
    4.  
    5. public delegate void SendData(object sender);  
    6.  
    7.    
    8.  
    9. // Create instance  
    10.  
    11.    
    12.  
    13. public SendData sendData;  
    14.  

    在Form2的按钮单击事件或其它事件代码中:

            
    1. if(sendData != null)  
    2.  
    3. {  
    4.  
    5.  sendData(txtBoxAtForm2);  
    6.  
    7. }  
    8.  
    9. this.Close(); //关闭Form2  

    在Form1的弹出Form2的代码中: 

            
    1. Form2 form2 = new Form2();  
    2.  
    3.  form2.sendData = new Form2.SendData(MyFunction);  
    4.  
    5.  form2.ShowDialog();  
            
    1. private void MyFunction(object sender)  
    2.  
    3. {  
    4.  
    5. textBox1.Text = ((TextBox)sender).Text;  
    6.  
    7. }  

    C#开发和使用的技巧就给大家介绍到这里,希望会对大家有用。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多