using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
namespace ComboboxToTextboxdb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection cn = new SqlConnection(dbConnect.dbconnectivity());
SqlDataAdapter da;
DataTable dt;
SqlCommand cmd;
SqlDataReader dr;
//display data in to combobox
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * From StudentRegistration", cn);
dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["StudentName"] = "Select Student Name";
dt.Rows.InsertAt(dr, 0);
cmbStudentName.ValueMember = "StudentId";
cmbStudentName.DisplayMember = "StudentName";
cmbStudentName.DataSource = dt;
}
//display combobox selected data to textboxes
private void cmbStudentName_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
cmd = new SqlCommand("Select * From StudentRegistration where StudentName=@name", cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", cmbStudentName.Text);
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
txtrollno.Text = dr[0].ToString();
txtName.Text = dr[1].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
}
}
}
}