DataGridView绑定每行Tag(点击按钮返回绑定的Tag)

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("id",typeof(int));
            dt.Columns.Add("name",typeof(string));

            dt.Rows.Add(new Object[]{1,"zhangsan" });
            dt.Rows.Add(new Object[]{2,"lisi"});
            dt.Rows.Add(new Object[]{3,"wangwu"});

            dataGridView1.DataSource = dt;

            //循环绑定每行Tag
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                dataGridView1.Rows[i].Tag = dt.Rows[i]["id"];
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //判断是否至少选中一个单元格
            if (dataGridView1.SelectedCells.Count>0)
            {
                //获取行索引
                int index=dataGridView1.SelectedCells[0].RowIndex;
                //获取Tag值
                int id=(int)dataGridView1.Rows[index].Tag;
                //弹出消息
                MessageBox.Show(id.ToString());
            }
            else
            {
                MessageBox.Show("请至少选择一行数据!!!");
            }
        }
posted @ 2012-10-06 14:40  唔愛吃蘋果  阅读(2881)  评论(0编辑  收藏  举报