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; namespace VA11.__初识DataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //// TODO: 这行代码将数据加载到表“dB_OUHAI16040612DataSet._000”中。您可以根据需要移动或移除它。 //this._000TableAdapter1.Fill(this.dB_OUHAI16040612DataSet._000); //// TODO: 这行代码将数据加载到表“dB_OUHAIDataSet1._000”中。您可以根据需要移动或移除它。 //this._000TableAdapter.Fill(this.dB_OUHAIDataSet1._000); } private void button1_Click(object sender, EventArgs e) { //绑定模式 dataGridView1.DataSource = BindModeSource().Tables[0]; //获取源 //非绑定模式 dataGridView2.DataSource = NoBindSource(); } private void button2_Click(object sender, EventArgs e) { } //返回数据集 private DataSet BindModeSource() { string constr = "Server=H6;user=sa;pwd=123123;database=2016-04-22"; SqlConnection myCon = new SqlConnection(constr); DataSet myds = new DataSet(); try { myCon.Open(); string _sql = "select * from [000]"; SqlDataAdapter myda = new SqlDataAdapter(_sql, myCon); myda.Fill(myds, "mytable001"); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } finally { myCon.Close(); } return myds; } //返回表 private DataTable NoBindSource() { DataTable mydt = new DataTable(); mydt.Columns.Add("name",Type.GetType("System.String")); mydt.Columns.Add("money", Type.GetType("System.String")); mydt.Columns.Add("id", Type.GetType("System.Int32")); string[,] mystr ={ { "OH_15345", "100", "1" }, { "OH_00001", "200", "2" }, { "OH_000002", "300", "3" } }; for (int i = 0; i < mystr.Length/ 3; i++) { DataRow row = mydt.NewRow(); //新行 row[0] = mystr[i,0]; row[1] = mystr[i,1]; row[2] = i; mydt.Rows.Add(row); } return mydt ; } /// DataGridView 获取当前单元格 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { //获取行的索引 //1种方式 //int row = e.RowIndex + 1; //int col = e.ColumnIndex + 1; //2种方式 //int row = dataGridView1.CurrentCell.RowIndex+1; //int col = dataGridView1.CurrentCell.ColumnIndex + 1; //3 int row = dataGridView1.CurrentCellAddress.Y + 1; int col = dataGridView1.CurrentCellAddress.X + 1; //4 //int row = dataGridView1.CurrentRow.Index+1; //获取单元格内容value string cell=dataGridView1.Rows[row-1].Cells [col-1].Value.ToString () ; cell = dataGridView1.CurrentCell.Value.ToString(); MessageBox.Show("你点击的是第" + row+"行,第"+col+"列\n 内容为"+cell ); } } } |
|
来自: 时间剧毒 > 《第十五章:表格数据控件》