将sqlserve数据绑定到dataGridView中及一些操作

本文介绍了如何使用C#将数据库中的数据绑定到DataGridView控件,并实现点击DataGridView某一行时,将该行数据对应显示在多个textBox控件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:将数据绑定到dataGridView控件上。

string sqlconn = "server=.;database=student;integrated security=true";
            try
            {
                string sqlcom = "select * from student_info";
                SqlConnection conn = new SqlConnection(sqlconn);
                SqlDataAdapter da = new SqlDataAdapter(sqlcom, conn);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;
                dataGridView1.AllowUserToAddRows = false;
                conn.Close();
            }    

二:点击dataGridView的某一行将改行数据对应显示在textBox上。

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                snoTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_sno"].Value.ToString();
                nameTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_name"].Value.ToString();
                sexTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_sex"].Value.ToString();
                ageTextBox.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["stu_age"].Value.ToString();
            }
            catch (Exception a)
            {
                MessageBox.Show(a.ToString());
            }
        }

转载于:https://www.cnblogs.com/luoyanghao/p/6082596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值