Binding Combobox with database - c#

I have combobox in my form which display value from database. I want one default value so I use .text property also and on selected index changed event the label display the corresponding value of the database the code is not working
string cstr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
private void AddStock_Load(object sender, EventArgs e)
{
bindcombo();
}
private void bindcombo()
{
SqlConnection con = new SqlConnection(cstr);
SqlDataAdapter da = new SqlDataAdapter("SELECT Dname FROM dealer", con);
DataTable dt = new DataTable();
da.Fill(dt);
cmbdealer.DataSource = dt;
cmbdealer.DisplayMember = "Dname";
cmbdealer.Text = "select-Dealer";
con.Close();
}
private void cmbdealer_SelectedIndexChanged(object sender, EventArgs e)
{
dealerdetails();
}
private void dealerdetails()
{
SqlConnection con = new SqlConnection(cstr);
SqlCommand cmd = new SqlCommand("select * from dealer where Dname='" + cmbdealer.Text + "'", con);
con.Open();
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
{
lbdl.Text = re["Ddlno"].ToString();
lbgst.Text = re["Dgstno"].ToString();
lbadd.Text = re["Daddress"].ToString();
}
}
the above code is working fine but when the form is load all the 3 label shows the database value of the first entry of my dealer table without selecting and value from combobox.

Related

Filter listbox data by using datagridview cell

I want to filter listbox data by using datagridview cell instead of using textbox.I am using the following code.
private void searchLedger(string value)
{
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from LedgerCreation Where ledgerName like #LedgerName and AddClassification = #AddClassification order by LedgerName", cn);
cmd.Parameters.AddWithValue("#AddClassification", "Cash/Bank");
cmd.Parameters.AddWithValue("#LedgerName", "%" + value + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
LstReceipt.DataSource = table;
LstReceipt.DisplayMember = "LedgerName";
cn.Close();
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
searchLedger(dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString());
}
}

datagridview event causing datagridview to no fill up properly

Both of these functions are working fine, one should fill up datagrid with data, the other, should be triggered when i select a row from the first datagrid. But for some reason the second function is causing datagrid to fill just one row of data.
private void fillDataGrid(DataGridView dg, string query) {
OracleCommand cmd = new OracleCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
try {
cmd.ExecuteNonQuery();
oda.Fill(dt);
**dg.DataSource = dt;**
}
catch(Exception e) {
MessageBox.Show(e.ToString());
}
}
This function is called when i load the form, and it is working fine on its own. But when the next function is causing some kind of problem and i don't know why.
private void dataGridView1_SelectionChanged_1(object sender, EventArgs e)
{
String s = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
String upit = "select dn.* from detaljinarudzbe dn, narudzba n where dn.nid = n.nid and n.jmbg = " + s + "";
fillDataGrid(dataGridView2, upit);
}
It is working fine, but i get just one row in first datagridview. And expection says
system.argument out of range exception:must be non negative and less
than the size of collection
Caused by the ** line in first method. I don't get why is the event causing this problem. when i use the second function on a button it is working fine.
You can try (I using SQL Server) : attention check SelectedRows[0] by SelectedRows.Count
private void fillDataGrid(DataGridView dg, string query) {
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlDataAdapter oda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try {
conn.Open();
cmd.ExecuteNonQuery();
oda.Fill(dt);
conn.Close();
dg.DataSource = dt;
}
catch(Exception e) {
MessageBox.Show(e.ToString());
}
finally
{
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if(dataGridView1.SelectedRows.Count > 0)
{
String s = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
String upit = "Select * from CARD_NO where CT_ID = " + s + "";
fillDataGrid(dataGridView2, upit);
}
}
private void Form1_Load(object sender, EventArgs e)
{
fillDataGrid(dataGridView1, "Select * from CARD_TYPE");
}

Displaying text in texbox from databse based on selected items from combobox

I have basically a combobox and a text box.
The combobox consists of subject code, whereas the textbox consists of a subject name which is stored in the database.
Is there any way that when an item from combobox is selected, it automatically displays the subject name based on the selected subject code, which will be from the database?
Below is my code, but it is not working.
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter oda1 = new OleDbDataAdapter("select subject_code from subjectinfo", con);
DataTable dt1 = new DataTable();
oda1.Fill(dt1);
comboBoxSubjectCodeUpdate.DataSource = dt1;
comboBoxSubjectCodeUpdate.DisplayMember = "subject_code";
comboBoxSubjectCodeUpdate.SelectedIndex = -1;
con.Close();
}
private void comboBoxSubjectCodeUpdate_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "select subject_abbreviation from subjectinfo where subject_code ='" + comboBoxSubjectCodeUpdate.Text + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["subject_abbreviation"].ToString();//column name should be that you want to show on textbox
}
}

How to do a table look up so that my dropdownlist will display the data that I want

I have two tables called facility and Facilitytype_lookup table with relationship with each other using fac_type column field. In the first drop down list I populate the data using fac_type field on facility table, and if the selected fac_type field value is selected, for example selecting LT, the fac_code belonging to that fac_type will be displayed on the second drop down list which is L.337 and L.338 like in the screenshots. The problem is I want the first dropdownlist names to be in full. For etc MR as Meeting Room, DR as discussion Room, LT for leture Theatre. That';s why I created another table called Facilitytype_lookup with the column field called fac_name. How do I make the first drop down list names to be in full names using column field fac_name??
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_TYPE from FACILITY", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_TYPE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}
Edited, first dropdownlist will display fac_name values, but after choosing any option in first drop down list, second drop down list doesn't come out anything
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct facility.FAC_TYPE, facilitytype_lookup.fac_name from FACILITY inner join facilitytype_lookup ON facility.fac_type=facilitytype_lookup.fac_type", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacilityType.DataTextField = ds.Tables[0].Columns["FAC_name"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacilityType.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacilityType.DataBind(); //binding dropdownlist
ddlFacilityType.Items.Insert(0, new ListItem(" Select type", "0"));
}
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacilityType_SelectedIndexChanged(object sender, EventArgs e)
{
//string constr = ConfigurationManager.ConnectionStrings["serverConnectionString"].ToString(); // connection string
string constr = ConfigurationManager.ConnectionStrings["projectConnectionString"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE from FACILITY where FAC_TYPE='" + ddlFacilityType.SelectedValue.ToString() + "'", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlFacility.DataTextField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // text field name of table dispalyed in dropdown
// to retrive specific textfield name
ddlFacility.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlFacility.DataBind(); //binding dropdownlist
ddlFacility.Items.Insert(0, new ListItem(" Select room", "0"));
}
protected void ddlFacility_SelectedIndexChanged(object sender, EventArgs e)
{
Session["roomvalue"] = ddlFacility.SelectedValue;
if (ddlFacilityType.Text == "MR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "CR")
{
Response.Redirect("number1.aspx");
}
else if (ddlFacilityType.Text == "DR")
{
Response.Redirect("number1.aspx");
}
else
Response.Redirect("number2.aspx");
}
}

getting value of combobox to textbox

using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}

Categories