DropDownLists Issue ASP.NET - c#

I really have a serious issues with postback, I have 3 dropdownlists, the first one contain data from a database, it's the countries, the second is the same but for the cities who depends the selected value on the first dropdownlist which is the countries, and the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities.
So the first two dropdownlists work perfectly, but the third dropdownlist will never work even with autopostback true and false, it will always refresh on to the first value and I wrote if(!IsPostback) so I really I'm frustrated about this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;
namespace Hijazi_Airlines
{
public partial class Book : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["HAirlines"].ConnectionString);
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
Sign.Text = "Sign Out";
}
else
{
}
gather_countries();
gather_cities();
gather_Tocountries();
gather_Tocities();
}
private void gather_date()
{
try
{
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmd.ExecuteReader();
reader.Read();
Response.Write(reader[0].ToString());
sqlcon.Close();
}
catch
{
}
sqlcon.Close();
}
private void gather_cities()
{
FromCit.Items.Clear();
string cities = "select * from Cities where country_id = " + FromCount.SelectedValue;
CountriesAndCities(cities, FromCit);
}
private void gather_Tocities()
{
ToCit.Items.Clear();
string cities = "select * from Cities where country_id = " + To.SelectedValue;
CountriesAndCities(cities, ToCit);
}
private void gather_countries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
private void gather_Tocountries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, To);
}
private void CountriesAndCities(string query, DropDownList dp)
{
SqlCommand sqlcmdC = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmdC.ExecuteReader();
while (reader.Read())
{
ListItem item = new ListItem();
item.Text = reader[1].ToString();
item.Value = reader[0].ToString();
dp.Items.Insert(0, item);
}
sqlcon.Close();
}
protected void Hom_Click(object sender, EventArgs e)
{
Response.Redirect("Home.aspx");
}
protected void SignIN_Click1(object sender, EventArgs e)
{
if (Sign.Text == "Sign Out")
{
Session.RemoveAll();
Session.Abandon();
Sign.Text = "Sign In";
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void Contact_Click(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}
protected void To_SelectedIndexChanged(object sender, EventArgs e)
{
gather_Tocities();
}
protected void Airlin_SelectedIndexChanged(object sender, EventArgs e)
{
gather_date();
}
}
}

Problem is here:
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
You said that the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities. But in the above code you are selecting the value of third dropdown which makes no sense as it doesn't have any value.
So instead of above code, change the id value to this:
string query = "SELECT Depart FROM Flights where Airlines_id=" + YourCityDropDownId.SelectedValue;
Check this and let me know.

Your problem is permanently recreate ddl.
gather_Tocountries();
gather_Tocities();
Well, for solution this problem, you need after created your ddls set selected value for ToCit and To ddl.
ToCit.SelectedValue = yourValue; //Something like this;
But code which you wrote is not productive, because you each time call database
if you wanna init your ddl after select in prev, just call your method
CountriesAndCities in SelectedIndexChanged. First init you can do in pageInit or pageLoad but with use if(isPostBack){your first ddl init}
for example
PageLoad(){
if(IsPostBack){
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
}
For other ddl the same
then
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}

Related

How to display the correct amount of records for a chart in visual studios c#

Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button

Refresh another forms DataGridView from button click

I have a form (customersForm) displaying a datagridview with customer information. And a second form (viewForm) which allows the user to view, edit,delete and update selected datagridview row. When I click update, or delete i'd like the datagridview on the customerForm to refresh displaying the updated data. How can I do this from a button click?
This is the viewForms complete code:
using System;
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.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class viewForm : Form
{
DataRowView Data = null;
public viewForm(DataRowView dr)
{
InitializeComponent();
Data = dr;
}
private void closeBTN_Click(object sender, EventArgs e)
{
this.Close();
}
private void viewForm_Load(object sender, EventArgs e)
{
refTxt.Text = Data["Reference"].ToString().Trim();
firstTxt.Text = Data["First Name"].ToString().Trim();
surenameTxt.Text = Data["Surename"].ToString().Trim();
address1Txt.Text = Data["Address Line 1"].ToString().Trim();
address2Txt.Text = Data["Address Line 2"].ToString().Trim();
countyTxt.Text = Data["County"].ToString().Trim();
postTxt.Text = Data["Post Code"].ToString().Trim();
contactTxt.Text = Data["Contact Number"].ToString().Trim();
emailTxt.Text = Data["Email Address"].ToString().Trim();
}
private void deleteBTN_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Customer information will be perminantly deteled. Do you with to continue? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "delete from customersTBL where Reference ='" + this.refTxt.Text + "';";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Customer information has been deleted", "Deleted Sucessfully");
while (myReader.Read())
{
}
MessageBox.Show("Please exit the Customers window and re-open to update the table");
this.Close();
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
int UserID = Convert.ToInt32(refTxt.Text);
UpdateDataBase( UserID );
editBTN.Text = "Edit";
deleteBTN.Visible = true;
notEditable = true;
}
else
{
deleteBTN.Visible = false;
editBTN.Text = "Update";
deleteBTN.Visible = false;
notEditable = false;
}
firstTxt.ReadOnly = notEditable;
surenameTxt.ReadOnly = notEditable;
address1Txt.ReadOnly = notEditable;
address2Txt.ReadOnly = notEditable;
countyTxt.ReadOnly = notEditable;
contactTxt.ReadOnly = notEditable;
emailTxt.ReadOnly = notEditable;
postTxt.ReadOnly = notEditable;
}
private void UpdateDataBase(int customerID)
{
if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = #"update customersTBL set [First Name] = #fname,
surename = #sur, [Address Line 1] = #addr1,
[Address Line 2] = #addr2, County = #county,
[Post Code] = #pcode, [Email Address] = #mail, [Contact Number] = #ctNo
WHERE Reference = #id";
using (SqlCeConnection conDataBase = new SqlCeConnection(constring))
using (SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("#fname", this.firstTxt.Text);
cmdDataBase.Parameters.AddWithValue("#sur", this.surenameTxt.Text);
cmdDataBase.Parameters.AddWithValue("#addr1", this.address1Txt.Text);
cmdDataBase.Parameters.AddWithValue("#addr2", this.address2Txt.Text);
cmdDataBase.Parameters.AddWithValue("#county", this.countyTxt.Text);
cmdDataBase.Parameters.AddWithValue("#pcode", this.postTxt.Text);
cmdDataBase.Parameters.AddWithValue("#mail", this.emailTxt.Text);
cmdDataBase.Parameters.AddWithValue("#ctNo", this.contactTxt.Text);
cmdDataBase.Parameters.AddWithValue("#id", customerID);
int rowsUpdated = cmdDataBase.ExecuteNonQuery();
if (rowsUpdated == 0)
MessageBox.Show("No customer found to update");
MessageBox.Show("Customer information sucessfully updated", "Update Sucessfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The complete code for customerForm:
using System;
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.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class customerForm : Form
{
public customerForm()
{
InitializeComponent();
}
public void customerForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'lWADataBaseDataSet.customersTBL' table. You can move, or remove it, as needed.
timer1.Start();
this.lWADataBaseDataSet.EnforceConstraints = false;
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
}
addForm addForm = new addForm();
private void addBTN_Click(object sender, EventArgs e)
{
if (addForm == null || addForm.IsDisposed == true)
addForm = new addForm();
addForm.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count = customersTBLBindingSource.Count;
statusLBL.Text = "You currently have "+count.ToString()+" customer(s) stored in this database";
}
searchForm searchForm = new searchForm();
private void searchBTN_Click(object sender, EventArgs e)
{
if (searchForm == null || searchForm.IsDisposed == true);
searchForm = new searchForm();
searchForm.ShowDialog();
}
}
}
There is a lot you don't specify in your question, but let's assume this scenario:
When customerView is shown, you call the database to fill a DataGridView with customer details. At some point you either dbl-click on a DGV row, or you select a row and click a button, and then show viewForm, passing in the data in the currently selected row. Again, you don't specify how this is done, but let's assume you pass in a Data Transfer Object of some kind.
Once done editing, you click a button, save the changes to the database, then close viewForm.
According to your comments this is the general workflow you have in your application now.
In this case, you can simply re-fetch the data, as you did when first showing customerView when the viewForm.ShowDialog() method returns.
Unless there is something else I don't get, this can be easily done like this:
//customerForm
private void button1_Click(object sender, EventArgs e)
{
ViewFormClass viewForm = new ViewFormClass();
viewForm.SetCustomerData(dataObject);
viewForm.ShowDialog(); // will stop here waiting for viewForm to close
this.FetchCustomerData();
}
where FetchCustomerData() is the same method you called when opening customerView. In there you would typically fetch the data and bind it to controls.
Cheers
EDIT:
As per your own code, with a simple modification:
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}

ASP.NET Manual ListBox Filters for GridView

I have multiple ListBoxes as Categories, Departments, Faculties etc. And I have a GridView populated from database (MSSQL) in code-behind. I will use ListBoxes as filters.
For example, when i choose a category from CategoriesListBox, the GridView will show only the entries in this category. And when I also choose a Department, the GridView will show only the entries in selected category and department.
I suppose that I will do it by use of selectedIndexChanged event of ListBoxes. My aspx code is:
public partial class Default : System.Web.UI.Page
{
private string constr = MY_CONNECTION_STRING;
protected void Page_Load(object sender, EventArgs e)
{
FillGridView();
}
protected void FillGridView()
{
string Query = "SELECT * FROM Entry WHERE Category = '" + SelectedCategory +"' AND Department = '" + SelectedDepartment +"'";
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(Query, conn);
try
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("Hata: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedCategory value and re-fill GridView
}
protected void DepartmentsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Here I want to get SelectedDepartment value and re-fill GridView
}
}
Thanks for help.
you can do it by select from your table where CategoryName =#parameter in your connection string
#parameter is your listbox selectedItem or selected value.
Using your own code, why not pass the category and department to the FillGridView? And if one of those are null it would mean no filter at all. So, something like this:
protected void CategoriesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
FillGridView(lbCategory.SelectedItem.ToString(), lbDepartment.SelectedItem.ToString());
}
The same would be applied on the DepartmentsListBox_SelectedIndexChanged event.
Then change the FillGridView function to:
protected void FillGridView(string SelectedCategory, string SelectedDepartment)
Also, if I may I'd suggest to gather all the table contents at once, save data to an in-memory copy and filter them from said copy, this would enable a much more fast and better user experience imo.
Edit:
if (selectedCategory.Trim() == "")
selectedCategory = "IS NOT NULL";
else
selectedCategory = " = \'" + selectedCategory.Trim() + "\'";
if (selectedDepartment.Trim() == "")
selectedDepartment = "IS NOT NULL";
else
selectedDepartment = " = \'" + selectedDepartment.Trim() + "\'";
string Query = "SELECT * FROM Entry WHERE Category " + SelectedCategory + " AND Department " + SelectedDepartment;
Add it to the beginning of the FillGridView function (this is just a quick & easy hack, not the best solution).

How do you select data from MySQL database for it to be used in Combo Box Selection?

So usually when you create a combo box you'll be the one to put the value of the selection but I want the data in my combo box will be selected from my database mysql. How am I going to do that?
I am stuck at selecting data from my sql to combo box!
Here's my code so far!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection connection = null;
string hostname = "localhost";
string database = "aparece_hoteldb";
string username = "root";
string password = "";
connection = new MySqlConnection("host=" + hostname +
";database=" + database +
";username=" + username +
";password=" + password + ";");
string table = "reservations";
string query = "SELECT * FROM " + table;
connection.Open();
MySqlDataAdapter da_res = null;
DataSet ds_res = null;
ds_res = new DataSet();
da_res = new MySqlDataAdapter(query, connection);
da_res.Fill(ds_res, table);
dataGridView2.DataSource = ds_res.Tables[table];
}
private void label2_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
OK, so binding a list of data to a combo box, especially when it's one you've already got, is going to be pretty straight forward. So, after this line:
dataGridView2.DataSource = ds_res.Tables[table];
let's add a few more:
comboBox1.DisplayMember = "YourDisplayField";
comboBox1.ValueMember = "YourValueField";
comboBox1.DataSource = ds_res.Tables[table];
and that will bind the data to the combo box. But let's break this down. The DisplayMember is the field value that you want the user to see. Often times this is a name or a brief description of the row. The ValueMember is the field you want bound to the SelectedValue property. When the user selects an item in the combo box the SelectedValue will be set to the value of that field.
Now you can consume a better event that SelectedIndexChanged, now you can consume SelectedValueChanged. Every time the user selects a new value that event will fire and you can do with it what you need.
You could get the actual DataRow if you wanted by casting the SelectedItem property of the combo box like this:
var row = comboBox1.SelectedItem as DataRow;
or you could just grab that value and do something with it:
var val = comboBox1.SelectedValue;
and you could cast that to whatever type the ValueMember field is. If you set it to an int field then you might do something like this:
var val = (int)comboBox1.SelectedValue;
if it's a string field then maybe something like this:
var val = comboBox1.SelectedValue as string;
Assuming you get a single column returned by your sql you could set the datasource of the combobox to populate it from the datatable or dataset.
comboBox1.DataSource = myDataTable;
//inside the FORM_LOAD,
private void Form7_Load(object sender, EventArgs e){
cboFloor.SelectedIndex = -1;
cboFloor.DropDownStyle = ComboBoxStyle.DropDownList;
GetFloor();
}
//Create a Function and insert this code.
private voide GetFloor{
string query = #"SELECT DISTINCT floor FROM tbroom ORDER BY floor ASC";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cboFloor.Items.Add(rdr["floor"]);
}
}
catch (MySqlException mysqlex)
{
MessageBox.Show(mysqlex.Message.ToString());
}
finally
{
con.Close();
}}

Getting one data from another table in DropownList with AutoPostBack

I have a Customer table --> CustomerNumber and CustomerName columns
I have a Sales table --> CustomerName columns
I have a Label (represent CustomerNumber) and a DropDownList (represent CustomerName)
I getting to DropDownList Sales table --> CustomerName with SqlDataSource.
I want automaticly (with AutoPostBack) filling Label with CustomerNumber which CustomerName selected in DropDownList
Example SQL:
select A.CustomerNumber
from Customer A, Sales B
where B.CustomerName = DropDownList1.SelectedItems.Value
I'm thinking like this.
How can i do that?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
Try this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(-1 != DropDownList1.SelectedIndex)
{
using(SqlConnection connection = new SqlConnection("connectionString"))
{
connection.Open();
using(SqlCommand command = new SqlCommand("SELECT A.CUSTOMERNUMBER FROM CUSTOMER A, SALES B WHERE B.CUSTOMERNAME = #CustomerName"))
{
command.Connection = connection;
command.Parameters.AddWithValue("#CustomerName", DropDownlist1.SelectedValue.ToString());
this.Label1.Text = command.ExecuteScalar().ToString();
}
}
}
}
Hope it works. Disclaimer : I didn't tested the code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedName = DropDownList1.SelectedValue;
string sqlQuery = "select A.CustomerNumber from Customer A, Sales B where B.CustomerName = '" + DropDownList1.SelectedValue + "'";
// pass you sql query to command object and call execute scalar method
label1.Text = dbCommand.ExecuteScalar().ToString();
}
What do ExecuteScalar do?

Categories