I have a table product(productid , productName , productRate).....for product name i have given a combo box and for rate a textbox...
what i want is.....when i select an item from combo box its respective rate should be set to corresponding rate textbox....!!!
Loading
Satyapriya NayakPosted Mar 7, 2013, 8:15 AM
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Combobox
{
public partial class Form1 : Form
{
string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["dsn"];
OleDbCommand com;
OleDbDataAdapter oda;
DataSet ds;
string str;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Choose productName");
OleDbConnection con = new OleDbConnection(ConnectionString);
con.Open();
str = "select * from product";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader["productName"]);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = "";
OleDbConnection con = new OleDbConnection(ConnectionString);
con.Open();
str = "select * from product where productName='" + comboBox1.Text.Trim() + "'";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
textBox1.Text = reader["productRate"].ToString();
}
con.Close();
reader.Close();
}
}
}
Mustaq KhanPosted Mar 8, 2013, 2:29 AM
Vishal GilbilePosted Mar 7, 2013, 8:06 AM
Mustaq KhanPosted Mar 7, 2013, 8:02 AM
Vishal GilbilePosted Mar 7, 2013, 7:38 AM
There are two case to achieve this functionality,
case 1: when the product names are unique: In such case what you can do is when you are binding the values of a database column productName to the combobox you can set the DataValueField property of the comboBox to the productRate Column and DataTextField property of the Combobox to Productname Column. And after binding all the values you have to handle the selectedindexchanged event of the combobox where you can set the textbox.Text=combobox.SelectedValue.ToString().
case 2: where the productNames are not unique: In this case what you can do is when you are binding the values of a database column productName to the combobox you can set theDataValueField property of the comboBox to the ProductID and DataTextField And DataMember to ProductName column. And after binding all the values you have to handle the SelectedIndexChanged event of the combobox where you have to search a record in the database product table where productName=comboxBox.SelectedItem.Text and ProductID=comboBox.SelectedValue. Get the data by using SqlDataReader and finally set the TextBox value to dr["ProductRate"].ToString();
Hope that solves your problem.
With Regards,
Vishal Gilbile.