DataGridView使用技巧
1 private void textBox1_TextChanged(object sender, EventArgs e) 2 { 3 dataGridView1.Visible = true; 4 String conStr = ConfigurationManager.ConnectionStrings[SoftwareDictionaryInsert.BASICDICTIONARY].ConnectionString; 5 SqlConnection conn = new SqlConnection(conStr); 6 7 try 8 { 9 conn.Open(); 10 string sql = string.Format("select softwareID AS 软件编码,softwareName AS 软件名称,deletedFlag AS 停用标志 from SoftwareDictionary where deletedFlag = '0' and softwareName like '%{0}%'",textBox1.Text); 11 SqlCommand cmd = new SqlCommand(sql,conn); 12 DataTable dt_Result = new DataTable(); 13 SqlDataAdapter ada = new SqlDataAdapter(cmd); 14 ada.Fill(dt_Result); 15 dataGridView1.DataSource = dt_Result; 16 17 this.dataGridView1.Rows[0].Selected = true; 18 } 19 catch(Exception ex) 20 { 21 MessageBox.Show("程序允许错误,错误为:"+ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Error); 22 } 23 finally 24 { 25 conn.Close(); 26 } 27 } 28 29 30 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 31 { 32 if (keyData == Keys.Up)//上键 33 { 34 int index = dataGridView1.CurrentCell.RowIndex; 35 36 if (index > 0) 37 { 38 dataGridView1.CurrentCell = dataGridView1.Rows[index--].Cells[0]; 39 dataGridView1.Rows[index].Cells[0].Selected = true; 40 } 41 return true; 42 } 43 if (keyData == Keys.Down)//下键 44 { 45 /* 46 int index = dataGridView1.CurrentCell.RowIndex; 47 if (index < dataGridView1.RowCount - 1) 48 { 49 dataGridView1.CurrentCell = dataGridView1.Rows[index++].Cells[0]; 50 dataGridView1.Rows[index].Cells[0].Selected = true; 51 } 52 */ 53 54 if (dataGridView1.CurrentCell != null) 55 { 56 int index = dataGridView1.CurrentCell.RowIndex; 57 if (index < dataGridView1.RowCount - 1) 58 { 59 dataGridView1.CurrentCell = dataGridView1.Rows[index++].Cells[0]; 60 dataGridView1.Rows[index].Cells[0].Selected = true; 61 } 62 } 63 else 64 { 65 MessageBox.Show("软件字典数据为空!", "提示"); 66 } 67 68 return true; 69 } 70 if (keyData == Keys.Enter)//Enter键 71 { 72 dataGridView1_CellMouseClick(null, null); 73 } 74 return base.ProcessCmdKey(ref msg, keyData); 75 } 76 77 78 private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 79 { 80 /* 81 * 当软件字典为空或者(deleted全为1)时, 82 * textBox录入值后,检索不到数据 83 * 这时候,textBox中有值,是无效值。 84 * 如果此时误点停用,就应该提示报错。 85 * */ 86 if (dataGridView1.CurrentCell != null) 87 { 88 DataGridViewRow row_obj = dataGridView1.CurrentRow; 89 int row = row_obj.Index; 90 softwareName = dataGridView1.Rows[row].Cells[1].Value.ToString(); 91 textBox1.Text = softwareName; 92 dataGridView1.Visible = false; 93 } 94 else 95 { 96 MessageBox.Show("填充数据不是有效数据!", "提示"); 97 } 98 99 }