本文彙整 33 個 C# 開發常見問題與解決方案,涵蓋 DataGrid 自訂、WinForms 控制技巧、ADO.NET/SQL 技巧、Excel 匯出、安裝部署、跨表單傳值等實務主題,每則附程式碼可直接參考套用。
DataGridTableStyle + DataGridTextBoxColumn 設定 MappingName 與 HeaderText。WHERE col IS NULL。AcceptButton 屬性,或在 KeyPress 事件判斷 e.KeyChar == (char)13。numeric(15) 或 decimal(15,0)。WHERE col LIKE '%' + @param + '%'。KeyPress 事件處理 e.KeyChar == 13。int val = int.Parse(cmd.ExecuteScalar().ToString())。DataColumn,Expression = "Parent.ParentCol"。SUBSTRING(col, start, len) 或 Oracle SUBSTR。DropDownStyle = DropDownList。CONVERT(varchar(10), date, 120) 或 FORMAT(date, 'yyyy-MM-dd')。DataColumn.Expression = "Col1 + Col2" (SQL Server) / "Col1 || Col2" (Oracle)。CASE WHEN col LIKE '%(%' THEN SUBSTR(col, INSTR(col,'(')+1, INSTR(col,')')-INSTR(col,'(')-1) END。MouseWheel += (s,e)=> dataGrid.Select();。KeyPress 事件 SendKeys.Send("A"); e.Handled=true;。WindowState = FormWindowState.Maximized。DateTime.Now,SQL Server GETDATE()。dataGrid[row, col] (索引器)。dt.Select("City='Taipei'").Length。range.NumberFormat = "0000"。// 完整匯出範本:含自訂標題、邊框、置中、分頁列印標題、頁碼
private void ExportToExcel(DataSet ds)
{
Excel.Application excel = new Excel.Application();
excel.Workbooks.Add(true);
Excel._Worksheet ws = (Excel._Worksheet)excel.ActiveSheet;
DataTable dt = ds.Tables["table"];
int r = 1, c = 1;
// 標題列 (使用 TableStyle 自訂標題)
foreach (DataGridColumnStyle colStyle in dataGrid1.TableStyles[0].GridColumnStyles)
ws.Cells[r, c++] = colStyle.HeaderText;
// 資料列
foreach (DataRow row in dt.Rows)
{
c = 1; r++;
foreach (DataColumn col in dt.Columns)
ws.Cells[r, c++] = row[col];
}
// 邊框
Excel.Range rng = ws.get_Range(ws.Cells[1,1], ws.Cells[dt.Rows.Count+1, dt.Columns.Count]);
rng.Borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;
rng.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
rng.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
// 指定欄置中
ws.Columns[3].HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
// 每頁列印標題列
ws.PageSetup.PrintTitleRows = "$1:$1";
// 頁腳頁碼
ws.PageSetup.CenterFooter = "第 &P 頁 / 共 &N 頁";
excel.Visible = true;
}
// 長時間迴圈中更新 UI 需呼叫 DoEvents
dataGrid1.CaptionText = $"匯出中: {current}/{total}";
Application.DoEvents(); // 處理訊息佇列,讓 UI 重繪
// Flash ActionScript
fscommand("exec", "MyApp.exe");
// 需發布為 .exe,並在同目錄建立 fscommand 資料夾放入 MyApp.exe
dataGrid1.Select();
SendKeys.Send("{PGUP}"); // 上一頁
SendKeys.Send("{PGDN}"); // 下一頁
SendKeys.Send("^{LEFT}"); // Ctrl+左
SendKeys.Send("^{RIGHT}"); // Ctrl+右
dataGrid1.DataSource = ds; dataGrid1.DataMember = "ParentTable";
dataGrid2.DataSource = ds; dataGrid2.DataMember = "ParentTable.RelationName";
// AssemblyInfo.cs
[assembly: AssemblyVersion("1.0.*")] // Build = 從 2000/1/1 起的天數, Revision = 秒數/2
sn -k key.snk
// AssemblyInfo.cs: [assembly: AssemblyKeyFile("..\\..\\key.snk")]
// 編譯 DLL → gacutil /i MyLib.dll
SELECT * FROM tbl WHERE ASCII(SUBSTR(col,1,1)) BETWEEN ASCII('A') AND ASCII('Z')
var fvi = FileVersionInfo.GetVersionInfo(Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(fvi.FileVersion);
Setup.exe、.msiMyInstallerOverride Install() 讀取資源執行 SQL// 三層遞迴綁定
foreach (DataRow r1 in ds.Tables["A1"].Rows)
{
TreeNode n1 = tree.Nodes.Add(r1["Name"].ToString());
foreach (DataRow r2 in r1.GetChildRows("A1A2"))
{
TreeNode n2 = n1.Nodes.Add(r2["Name"].ToString());
foreach (DataRow r3 in r2.GetChildRows("A2A3"))
n2.Nodes.Add(r3["Name"].ToString());
}
}
// Form2
public delegate void SendDataHandler(object sender);
public event SendDataHandler SendData;
private void btnOK_Click(object s, EventArgs e)
{
SendData?.Invoke(txtInput);
Close();
}
// Form1
Form2 f2 = new Form2();
f2.SendData += (sender) => txtResult.Text = ((TextBox)sender).Text;
f2.ShowDialog();
這 33 個技巧涵蓋了 C# 開發中高頻遇到的問題,建議收藏備查。實務上應優先考慮現代框架(如 EF Core、ClosedXML、WPF/MVVM)替代部分傳統做法,但核心邏輯仍具參考價值。