DataTable範例
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; //新增命名空間 for SQL Server
namespace DataTable_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//替代資料列樣式
dataGridView1.RowsDefaultCellStyle.BackColor = Color.AliceBlue;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightYellow;
}
private void btn_Load_Click(object sender, EventArgs e)
{
string ConnString;
ConnString = "Data Source =127.0.0.1;Initial catalog = DiskRecord;" +
"User id = sa;Password = 123";
string selectCmd = "select * from Title ";
dataGridView1.DataSource = Create_DataTable(selectCmd, "Title", ConnString);
dataGridView1.AutoResizeColumns();
}
public DataTable Create_DataTable(string SQLcmd, string TableName, string ConnString)
{
try
{
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(SQLcmd, conn);
DataSet ds = new DataSet();
da.Fill(ds, TableName);
conn.Close();
da.Dispose();
//回傳DataTable
return ds.Tables[TableName];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
}
}
留言列表