c# 開發中的小記錄

來源:互聯網
上載者:User
1.怎樣定製VC#DataGrid欄位標題?

  DataGridTableStyle dgts = new DataGridTableStyle();

  dgts.MappingName = "myTable"; //myTable為要載入資料的DataTable

  

  DataGridTextBoxColumn dgcs = new DataGridTextBoxColumn();

  dgcs.MappingName = "title_id";

  dgcs.HeaderText = "標題ID";

  dgts.GridColumnStyles.Add(dgcs);

  。。。

  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語句的預存程序怎樣寫?

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

  6.vc# winform中如何讓textBox接受斷行符號鍵訊息(假沒沒有按鈕的情況下)?

  private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

  {

  if(e.KeyChar != (char)13)

  return;

  else

  //do something;

  }

  7.為什麼(Int32)cmd.ExecuteScalar()賦值給Int32變數時提示轉換無效?

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

  8.DataSource為子表的DataGrid裡怎樣增加一個列以顯示母表中的某個欄位?

  在子表裏手動添加一個列。

  DataColumn dc = new DataColumn("newCol", Type.GetType("System.String"));

  dc.Expression = "Parent.parentColumnName";

  dt.Columns.Add(dc); //dt為子表

  9.怎樣使DataGrid顯示DataTable中某列的資料時只顯示某一部分?

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

  10.如何讓winform的combobox只能選不能輸入?

  DropDownStyle 屬性確定使用者能否在文本部分中輸入新值以及列表部分是否總顯示。

  值:

  DropDown --- 文本部分可編輯。使用者必須單擊箭頭按鈕來顯示列表部分。

  DropDownList --- 使用者不能直接編輯文本部分。使用者必須單擊箭頭按鈕來顯示列表部分。

  Simple --- 文本部分可編輯。列表部分總可見。

  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 col1||col2 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會失去焦點。怎樣解決?

  this.dataGrid1.MouseWheel+=new MouseEventHandler(dataGrid1_MouseWheel);

  private void dataGrid1_MouseWheel(object sender, MouseEventArgs e)

  {

  this.dataGrid1.Select();

  }

  15.怎樣把鍵盤輸入的‘+’符號變成‘A’?

  textBox的KeyPress事件中

  if(e.KeyChar == '+')

  {

  SendKeys.Send("A");

  e.Handled = true;

  }

  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後列印時每一頁顯示’當前頁/共幾頁’,怎樣實現?

  ①

  private void button1_Click(object sender, System.EventArgs e)

  {

  int row_index, col_index;

  

  row_index = 1;

  col_index = 1;

  

  Excel.ApplicationClass excel = new Excel.ApplicationClass();

  excel.Workbooks.Add(true);

  

  DataTable dt = ds.Tables["table"];

  

  foreach(DataColumn dcHeader in dt.Columns)

  excel.Cells[row_index, col_index++] = dcHeader.ColumnName;

  

  foreach(DataRow dr in dt.Rows)

  {

  col_index = 0;

  foreach(DataColumn dc in dt.Columns)

  {

  excel.Cells[row_index+1, col_index+1] = dr[dc];

  col_index++;

  }

  row_index++;

  }

  excel.Visible = true;

  

  }

  

  private void Form1_Load(object sender, System.EventArgs e)

  {

  SqlConnection conn = new SqlConnection("server=tao; uid=sa; pwd=; database=pubs");

  conn.Open();

  

  SqlDataAdapter da = new SqlDataAdapter("select * from authors", conn);

  ds = new DataSet();

  da.Fill(ds, "table");

  

  dataGrid1.DataSource = ds;

  dataGrid1.DataMember = "table";

  }

  ②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的上下、左右的滾動?

  dataGrid1.Select();

  SendKeys.Send("{PGUP}");

  SendKeys.Send("{PGDN}");

  SendKeys.Send("{^{LEFT}"); // Ctrl+左方向鍵

  SendKeys.Send("{^{RIGHT}"); // Ctrl+右方向鍵

  25.怎樣使兩個DataGrid綁定兩個主從關係的表?

  DataGrid1.DataSource = ds;

  DataGrid1.DataMember = "母表";

  ...

  DataGrid2.DataSouce = ds;

  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的版本號碼?

  Process current = Process.GetCurrentProcess();

  FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(current.MainModule.FileName);

  Console.WriteLine(myFileVersionInfo.FileVersion);

  30.怎樣製作一個簡單的winform安裝程式?

  ① 建一個WinForm應用程式,最最簡單的那種。運行。

  ② 添加新項目->安裝和部署項目,‘模板’選擇‘安裝嚮導’。

  ③ 連續二個‘下一步’,在‘選擇包括的項目輸出’步驟打勾‘主輸出來自’,連續兩個‘下一步’,‘完成’。

  ④ 產生。

  ⑤ 到項目目錄下找到Setup.exe(還有一個.msi和.ini檔案),執行。

  31.怎樣通過winform安裝程式在Sql Server資料庫上建表?

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

  類別:代碼;模板:安裝程式類。

  名稱:MyInstaller.cs

  ② 在SQL Server建立一個表,再[所有任務]—[產生SQL指令碼]。

  產生類似如下指令碼(注意:把所有GO語句去掉):

  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MyTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

  drop table [dbo].[MyTable]

  

  CREATE TABLE [dbo].[MyTable] (

  [ID] [int] NOT NULL ,

  [NAME] [nchar] (4) COLLATE Chinese_PRC_CI_AS NOT NULL

  ) ON [PRIMARY]

  

  

  ALTER TABLE [dbo].[MyTable] WITH NOCHECK ADD

  CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED

  (

  [ID]

  ) ON [PRIMARY]

  ③ [項目]—[添加現有項]。mytable.sql—[產生操作]-[內嵌資源]。

  ④ 將MyInstaller.cs切換到程式碼檢視,添加下列代碼:

  先增加:

  using System.Reflection;

  using System.IO;

  然後:

  private string GetSql(string Name)

  {

  try

  {

    Assembly Asm = Assembly.GetExecutingAssembly();

    Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);

    StreamReader reader = new StreamReader(strm);

    return reader.ReadToEnd();

  }

  catch (Exception ex)

  {

    Console.Write("In GetSql:"+ex.Message);

    throw ex;

  }

  }

  

  private void ExecuteSql(string DataBaseName,string Sql)

  {

  System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();

  sqlConn.ConnectionString = "server=myserver; uid=sa; password=; database=master";

  System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql,sqlConn);

  

  Command.Connection.Open();

  Command.Connection.ChangeDatabase(DataBaseName);

  try

  {

  Command.ExecuteNonQuery();

  }

  finally

  {

  Command.Connection.Close();

  }

  }

  protected void AddDBTable(string strDBName)

  {

  try

  {

  ExecuteSql("master","create DATABASE "+ strDBName);

  ExecuteSql(strDBName,GetSql("mytable.sql"));

  }

  catch(Exception ex)

  {

  Console.Write("In exception handler :"+ex.Message);

  }

  }

  

  public override void Install(System.Collections.IDictionary stateSaver)

  {

  base.Install(stateSaver);

  AddDBTable("MyDB"); //建一個名為MyDB的DataBase

  }

  ⑤ [添加新項目]—[項目類型:安裝和部署項目]—[模板:安裝項目]—[名稱: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設定好三個表之間的關係。

  

  foreach(DataRow drA1 in ds.Tables["a1"].Rows)

  {

   tn1 = new TreeNode(drA1["name"].ToString());

   treeView1.Nodes.Add(tn1);

   foreach(DataRow drA2 in drA1.GetChildRows("a1a2"))

   {

  tn2 = new TreeNode(drA2["name"].ToString());

  tn1.Nodes.Add(tn2);

  foreach(DataRow drA3 in drA2.GetChildRows("a2a3"))

  {

   tn3 = new TreeNode(drA3["name"].ToString());

   tn2.Nodes.Add(tn3);

  }

   }

  }

  33.怎樣從一個form傳遞資料到另一個form?

  假設Form2的資料要傳到Form1的TextBox。

  在Form2:

  // Define delegate

  public delegate void SendData(object sender);

  // Create instance

  public SendData sendData;

  在Form2的按鈕單擊事件或其它事件代碼中:

  if(sendData != null)

  {

   sendData(txtBoxAtForm2);

  }

  this.Close(); //關閉Form2

  在Form1的彈出Form2的代碼中:

  Form2 form2 = new Form2();

  form2.sendData = new Form2.SendData(MyFunction);

  form2.ShowDialog();

  ====================

  private void MyFunction(object sender)

  {

  textBox1.Text = ((TextBox)sender).Text;

  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.