c# datagridview選中當前單元格及單元格單擊事件

wisdomone1發表於2012-02-28

public partial class Form2 : Form
    {
        OracleDataAdapter oda;
        DataSet ds1;
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToAddRows = true;
            //如果選中DATAGRIDVIEW某行其中某個單元格(列)是空值,進行相應的特殊處理
            //data source,user id,password不區分大小寫
            OracleConnection con = new OracleConnection("data Source=orcl;user id=scott;password=system");
            OracleCommand comm = new OracleCommand();
            comm.Connection = con;
            comm.CommandText = "select deptno,dname,loc from dept";
            comm.CommandType = CommandType.Text;
            da= new OracleDataAdapter(comm);
            ds1 = new DataSet();
            oda.Fill(ds1);
            dataGridView1.DataSource = ds1.Tables[0];

        }


        //datagridview_cellcontentclick單擊單元格內容發生此事件
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
          
        }

        //cellclick單元格任何部分發生此事件
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //currentcell當前活動單元格 columnindex 當前活動單元格的索引

            // this.textBox1.Text = dataGridView1.SelectedCells[dataGridView1.CurrentCell.ColumnIndex]
            //檢視此單元格的值currentcell.value
            if (dataGridView1.CurrentCell.Value.ToString()=="")
            {
                MessageBox.Show("你選中的單元格無值");
            }
            this.textBox1.Text = dataGridView1.CurrentCell.Value.ToString() + dataGridView1.CurrentCell.ColumnIndex.ToString();
            //selectedcells.tostring返回型別的名字資訊,而不是單元格的內容,即顯示datagridviewselectedcellcollection
           // this.textBox1.Text = dataGridView1.SelectedCells.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //利用oraclecommandbuilder封裝oracledataadapter,然後用update來更新資料庫表
            OracleCommandBuilder cb = new OracleCommandBuilder(oda);
            oda.Update(ds1.Tables[0]);
        }

       
    }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-717324/,如需轉載,請註明出處,否則將追究法律責任。

相關文章