WinForm----DataGridview---连接数据库,以及双击一条数据,显示信息到Label控件,也可以是TextBox控件。
最终效果:
代码:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Configuration; 11 using System.Data.SqlClient; 12 13 namespace Test 14 { 15 public partial class Form1 : Form 16 { 17 string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString; 18 19 public Form1() 20 { 21 InitializeComponent(); 22 23 data(); 24 } 25 26 public void data() 27 { 28 using (SqlConnection con = new SqlConnection(constring)) 29 { 30 con.Open(); 31 32 string Sql = "select * from tb_Frinfo"; 33 34 DataTable dt = new DataTable(); 35 36 SqlDataAdapter dap = new SqlDataAdapter(Sql, con); 37 38 dap.Fill(dt); 39 40 this.dataGridView1.DataSource = dt; 41 } 42 } 43 44 private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 45 { 46 this.label1.Text = this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); 47 this.label2.Text = this.dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); 48 this.label3.Text = this.dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); 49 this.label4.Text = this.dataGridView1.SelectedRows[0].Cells[3].Value.ToString(); 50 this.label5.Text = this.dataGridView1.SelectedRows[0].Cells[4].Value.ToString(); 51 this.label6.Text = this.dataGridView1.SelectedRows[0].Cells[5].Value.ToString(); 52 this.label7.Text = this.dataGridView1.SelectedRows[0].Cells[6].Value.ToString(); 53 this.label8.Text = this.dataGridView1.SelectedRows[0].Cells[7].Value.ToString(); 54 } 55 56 } 57 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。