Open Windows Form.Add on DataGridview and the three Textboxes on the Windows Form.
In the above example I am creating it on emp table and my 3 columns are
id number,empname(varchar (20),salary number(20). In form load Retrive the data a emp Table and fill in the Datagridview.
When you click or Select a Row on DataGridview the particular selected row values
will display in Textboxes when we use the following code.
int i;
i = dataGridView1.SelectedCells[0].RowIndex;
textBox1.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();
textBox2.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
textBox3.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
before using this code you have to double click your DataGridview and write the
code in between the Private void dataGridView1_CellContentClick_(objectsender,DataGridViewCellEventArgs e) { //write above code here... }
when you selecte a row in datagrid ,the selected row Values will display in text boxes. Below is the output image:
below is the complete code:
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 WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlDataAdapter da; DataSet ds; int i; SqlConnection conn; private void Form1_Load(object sender, EventArgs e) { conn = new SqlConnection("connetion tring"); conn.Open(); da= new SqlDataAdapter("select * from emp", conn); SqlCommandBuilder builder = new SqlCommandBuilder(da); ds = new DataSet(); da.Fill(ds, "emp"); dataGridView1.DataSource = ds.Tables["emp"]; } Private void dataGridView1_CellContentClick_1
(objectsender,DataGridViewCellEventArgs e) { i = dataGridView1.SelectedCells[0].RowIndex; textBox1.Text = dataGridView1.Rows[i].Cells[0].Value.ToString(); textBox2.Text = dataGridView1.Rows[i].Cells[1].Value.ToString(); textBox3.Text = dataGridView1.Rows[i].Cells[2].Value.ToString(); } }
thanku so much
ReplyDelete