2014年2月12日 星期三

C# DataGridView, Read Cell Value

延續上一篇 C# DataGridView 連接ACCESS with SQL語法 

將database的資料連結到DataGridView後,下一個步驟當然就是對資料做Read/Wirte的動作
這一篇簡單的說明要如何Get/Read Cell的資料

可以透過DataGridView的屬性獲取資料,程式碼如下:
private void button1_Click(object sender, EventArgs e)
{
 textBox1.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
}


配合DataGridView的事件CellClick(如下圖),獲取點選的Cell資料
程式碼如下:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
 string strContent = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
 MessageBox.Show(strContent);
}
Sample Code Download

C# DataGridView 連接ACCESS with SQL語法

如何使用DataGridView連接ACCESS,使用簡單的SQL語法

使用到的物件
1. DataSet
2. OleDbDataAdapter 用來填入 DataSet 並更新資料來源

變數
strDatabase:Access檔案名稱
strsql: Connection String
strTableName:要讀取的Table Name

//OLE Naming Space
using System.Data.OleDb;

namespace DataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strDatabase = "C:\\FileDataBase.mdb";
            string strsql = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDatabase;
            string strTableName="TestTable";
            DataSet ds=new DataSet();
            OleDbDataAdapter oda;
            string strDataTable = "select * from " + strTableName;
            oda = new OleDbDataAdapter(strDataTable, strsql);
            oda.Fill(ds, strTableName);
            dataGridView1.DataSource = ds.Tables[strTableName];

        }
    }
}
Sample Code Download