Set value of combo box to collected value from source - c#

I have a form with two combo boxes which both have a list from a database. In this case one is a list of countries and based on the value selected there, the second list is updated to show only the cities that belong to the selected country. After that, the values are combined and stored in my program like "city, country".
When I open my form I retrieve that information and separate the values back to just country and city. All working. The trouble I have now is that the comboboxes should display the retrieved values if the correspond to a value found in the list/database. I tried as shown below, but that is not working. I guess it has something to do with adding a new row to the database to show "--Select Country--" and "--Select City--".
I hope you can point me in the right direction. Thank you all in advance for your replies.
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
public partial class FormPropertyEditor : Form
{
//Connect to local database.mdf
SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
#"C:\Users\gleonvanlier\AppData\Roaming\Autodesk\ApplicationPlugins\MHS Property Editor\Database.mdf;" +
"Integrated Security=True;Connect Timeout=30;User Instance=False;");
DataRow dr;
public FormPropertyEditor()
{
InitializeComponent();
ReadProperties();
refreshdata();
}
public void refreshdata()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCountries Order by CountryName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select Country--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCountry.ValueMember = "CountryID";
comboBoxCountry.DisplayMember = "CountryName";
comboBoxCountry.DataSource = dt;
comboBoxCountry.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCountry.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxCountry.SelectedValue.ToString() != null)
{
int CountryID = Convert.ToInt32(comboBoxCountry.SelectedValue.ToString());
refreshstate(CountryID);
}
}
public void refreshstate(int CountryID)
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from TblCities where CountryID= #CountryID Order by CityName", con);
cmd.Parameters.AddWithValue("CountryID", CountryID);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, 0, "--Select City--" };
dt.Rows.InsertAt(dr, 0);
comboBoxCity.ValueMember = "CityID";
comboBoxCity.DisplayMember = "CityName";
comboBoxCity.DataSource = dt;
comboBoxCity.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBoxCity.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void ReadProperties()
{
string progId = "Inventor.Application";
Type inventorApplicationType = Type.GetTypeFromProgID(progId);
Inventor.Application invApp = (Inventor.Application)Marshal.GetActiveObject(progId);
//Get the active document in Inventor
Document oDoc = (Document)invApp.ActiveDocument;
ReadProperties readProperties = new ReadProperties();
//Read Customer
string txtCustomer = readProperties.ReadCustomProperty("Customer", oDoc).ToString();
this.textBoxCustomer.Text = txtCustomer;
//Read Location
string txtLocation = readProperties.ReadCustomProperty("Location", oDoc).ToString();
try
{
string[] location = txtLocation.Split(',', ' ');
string city = location[0];
string country = location[1];
comboBoxCountry.SelectedValue = comboBoxCountry.FindString(country);
comboBoxCity.SelectedValue = comboBoxCity.FindString(city);
}
catch (Exception e)
{
string city = string.Empty;
string country = string.Empty;
}
}

This solved it:
comboBoxCountry.SelectedIndex = comboBoxCountry.FindStringExact(country);
comboBoxCity.SelectedIndex = comboBoxCity.FindStringExact(city);

Related

Invalid object name

The first one is function with query to access information about driver from table tblDDDDriver by using VehicleNumber which is one of the field or column name in tblDDDDriver.
The second one is what i coded to access that function.
Now when i click the button i shows the error Invalid object name 'tblDDDDriver'
public DataTable GetDriverByVehicalNumber(string VehicleNumber)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=tprojectDB;");
string sql = "select *from tblDDDDriver where VehicleNumber=#VehicleNumber";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#VehicleNumber", VehicleNumber);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
private void button6_Click(object sender, EventArgs e)
{
DataTable dt = dc.GetDriverByVehicalNumber(txtvehicleno.Text);
if (dt.Rows.Count > 0)
{
txtlicenseno.Text = dt.Rows[0]["LicenseNumber"].ToString();
txtlicensecategory.Text = dt.Rows[0]["LicenseCategory"].ToString();
txtissuedate.Text = dt.Rows[0]["IssueDate"].ToString();
txtrenewdate.Text = dt.Rows[0]["RenewDate"].ToString();
txtfullname.Text = dt.Rows[0]["FullName"].ToString();
txtdob.Text = dt.Rows[0]["DOB"].ToString();
txtaddress.Text = dt.Rows[0]["Address"].ToString();
string gender = dt.Rows[0]["Gender"].ToString();
if (gender == "Male")
{
txtgender.Text = " MALE";
}
else
{
txtgender.Text = "FEMALE";
}
txtvehicleno.Text = dt.Rows[0]["VehicleNumber"].ToString();
txthealthstaus.Text = dt.Rows[0]["HealthStatus"].ToString();
txtdrivertype.Text = dt.Rows[0]["DriverType"].ToString();
Image img;
byte[] bytimg = (byte[])dt.Rows[0]["Image"];
//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
ms.Write(bytimg, 0, bytimg.Length);
img = Image.FromStream(ms, true);
pictureBox1.Image = img;
}
}
DataTable dd = dc.GetMaxDeathNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dd.Rows.Count > 0)
{
txtdeathaccidentno.Text = dd.Rows[0]["DeathNumber"].ToString();
}
DataTable dM = dc.GetMaxMajorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dM.Rows.Count > 0)
{
txtmajoraccidentno.Text = dM.Rows[0]["MajorNumber"].ToString();
}
DataTable dm = dc.GetMaxMinorNo(Convert.ToDecimal(txtlicensenumber.Text));
if (dm.Rows.Count > 0)
{
txtminoraccidentno.Text = dm.Rows[0]["MinorNumber"].ToString();
}
DataTable dtrb = dc.GetTrafficRuleBroken(Convert.ToDecimal(txtlicensenumber.Text));
{
dataGridView1.DataSource = dtrb;
}
}

how to display comparison chart using ajax

I am trying to display ajax bar chart in my web page. But it is only displaying one value .
My db contains 3 columns(name, credit, debit) I want to display the credit debit values in chart. But the chart is only displaying one value. How can I modify the given below coding. Thank you.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if (prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select Name, Debit, Credit From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#name", SqlDbType.NVarChar);
prms[0].Value = ddlCountries.SelectedItem.Value.ToString();
DataTable dt = GetData(query, prms);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} -RunTimeReportChart", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
Data Base:
Actual Output:
The given below chart is only displaying the name and debit value. I want to display the credit value also. Please help me.
Something Like :
decimal[] z = new decimal[dt.Rows.Count];
z[i] = Convert.ToInt32(dt.Rows[i][2]);
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });

how to insert multiple value into combobox using dataset from database in c#

this is my code for multiple value in combobox. I have frmEntryHistory which entry a student id and his/her name in combobox , bookID and the title in combobox, and then date.
im using method on class library to get data from database and store them in dataset. And then i call that method on frmEntryHistory. I can appear ID-Tittle on combobox but not as record just name of columns on master_book table.
Please help me and sorry for confusing english. :)
// Method Library Class
public DataSet getBooks_ComboBox()
{
IDbDataAdapter adapter = null;
DataSet ds = null;
try
{
sb = new StringBuilder();
adapter = new MySqlDataAdapter();
comm = new MySqlCommand();
ds = new DataSet();
openConnection();
comm.Connection = conn;
sb.Append(#"select ID, ID + ' - ' + Title as Book from master_book");
comm.CommandText = sb.ToString();
adapter.SelectCommand = (MySqlCommand)comm;
adapter.Fill(ds);
closeConnection();
return ds;
}
catch (Exception ex)
{
return null;
}
}
//In my form Entry History
private void frmEntryHistory_Load(object sender, EventArgs e)
{
lblTgl.Text = DateTime.Now.ToString("dd/MM/yyyy");
Library lib = new Library();
DataSet ds = new DataSet();
//stored item into combobox
try
{
ds = lib.getBooks_ComboBox();
cmbBook.DataSource = ds.Tables[0];
cmbBook.DisplayMember = "Book";
cmbBook.ValueMember = "ID";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
what i want for output from combobox is ID - Title example : 1 - Novel asd, etc
After you fill the datatable, before you bind it to the combobox, you can create a new column to use. This example uses the pubs database:
DataSet1.titlesDataTable TitlesTable = new DataSet1.titlesDataTable();
titlesTableAdapter1.Fill(TitlesTable);
DataColumn DC = new DataColumn();
DC.ColumnName = "Test";
DC.DataType = typeof(string);
DC.Expression = string.Format("{0} + '-' + {1}", "title_id", "title");
TitlesTable.Columns.Add(DC);
comboBox1.DataSource = TitlesTable;
comboBox1.DisplayMember = "Test";
comboBox1.ValueMember = "title_id";

Dynamically update combobox based on user selection

I am not sure how postback works on WinForms, but I want to allow the ComboBox to update based on the user selection.
Currently when I change the selection of my first ComboBox, it doesn't change the items in the second dropdown. (only showing the first item by default)
In what ways can O alter this?
Code to what I have:
public ContentUploader()
{
InitializeComponent();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... re.OverallID = 1", conString))
{
DataTable dt = new DataTable();
sda.Fill(dt);
sections_drp.ValueMember = "ID";
sections_drp.DisplayMember = "DisplayName";
sections_drp.DataSource = dt;
}
}
sections_drp.SelectedIndexChanged += (o, e) => FillFirstChildren();
}
public void FillFirstChildren()
{
firstChild_drp.Items.Add("Select Item");
firstChild_drp.SelectedIndex = 0;
string sectionId = sections_drp.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT ... em.ItemID = ("+ sectionId +")", conString))
{
DataTable dt = new DataTable();
sda.Fill(dt);
firstChild_drp.ValueMember = "ID";
firstChild_drp.DisplayMember = "DisplayName";
firstChild_drp.DataSource = dt;
}
}
FillSecondChildren();
}
Winforms does not contain a post back. You will need to tie to the SelectedIndexChanged (or Item or Value) event to filter your second dropdown.
Example:
public void FillFirstChildren()
{
//Your Fill Logic Here
...
//Call FillSecondChildren on selection change
firstChild_drop.SelectedIndexChanged += (o, e) => FillSecondChildren();
}

Add an item to combobox before binding data from the database

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
You could either add the default text to the Text property of the combobox like this (preferred):
CBParent.Text = "<-Please select Category->";
Or, you could add the value to the datatable directly:
da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
public class ComboboxItem
{
public object ID { get; set; }
public string Name { get; set; }
}
public static List<ComboboxItem> getReligions()
{
try
{
List<ComboboxItem> Ilist = new List<ComboboxItem>();
var query = from c in service.Religions.ToList() select c;
foreach (var q in query)
{
ComboboxItem item = new ComboboxItem();
item.ID = q.Id;
item.Name = q.Name;
Ilist.Add(item);
}
ComboboxItem itemSelect = new ComboboxItem();
itemSelect.ID = "0";
itemSelect.Name = "<Select Religion>";
Ilist.Insert(0, itemSelect);
return Ilist;
}
catch (Exception ex)
{
return null;
}
}
ddlcombobox.datasourec = getReligions();
CBParent.Insert(0,"Please select Category")
You should add "Please select" after you bind data.
var query = from name in context.Version
join service in context.Service
on name.ServiceId equals service.Id
where name.VersionId == Id
select new
{
service.Name
};
ddlService.DataSource = query.ToList();
ddlService.DataTextField = "Name";
ddlService.DataBind();
ddlService.Items.Insert(0, new ListItem("<--Please select-->"));
There are two quick approaches you could try (I don't have a compiler handy to test either one right now):
Add the item to the DataTable before binding the data.
You should be able to simply set CBParent.Text to "<- Please Select Category ->" after you bind the data. It should set the displayed text without messing with the items.
void GetProvince()
{
SqlConnection con = new SqlConnection(dl.cs);
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT ProvinceID, ProvinceName FROM Province", con);
DataTable dt = new DataTable();
int i = da.Fill(dt);
if (i > 0)
{
DataRow row = dt.NewRow();
row["ProvinceName"] = "<-Selecione a Provincia->";
dt.Rows.InsertAt(row, 0);
cbbProvince.DataSource = dt;
cbbProvince.DisplayMember = "ProvinceName";
cbbProvince.ValueMember = "ProvinceID";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources