Setting value to ComboBoxs item #C - c#

I'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));

using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}

You need to set the data source of the combobox.

Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);

Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

Related

Set value of combo box to collected value from source

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);

only 1 record coming instead of multiple records in the model in c#

im getting only 1 row multiple times instead of getting multiple records. same record getting multiple times in the datatable and model.
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT
Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
m.DeviceDate =Convert.ToDateTime(deviceDate);
m.Units =Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);
Since the object is created before foreach, The object will be replaced with new entries all the time. Add Trans_energycons_ReportModel m = new Trans_energycons_ReportModel(); inside foreach
List<Trans_energycons_ReportModel> model = new List<Trans_energycons_ReportModel>();
using (SqlConnection con = new SqlConnection("constr"))
{
con.Open();
SqlCommand cmd_get_transformer_consumption = new SqlCommand(#"SELECT Date,units from Total_Power", con);
SqlDataAdapter da_get_trans_consumption = new SqlDataAdapter(cmd_get_transformer_consumption);
DataTable dt = new DataTable();
da_get_trans_consumption.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string deviceDate = row["Date"].ToString();
string units = row["units"].ToString();
//Create object here
Trans_energycons_ReportModel m = new Trans_energycons_ReportModel();
m.DeviceDate = Convert.ToDateTime(deviceDate);
m.Units = Convert.ToDouble(units);
model.Add(m);
}
}
return View(model);

Trying to return records from database using c#

This is my code which i'm trying to return records back into a listview by entering different ID's. But i only seem to get the first record back no matter which ID i enter. Any help would be appreciated.
private void FindRecord()
{
List<SprocParameter> paramsSQL = new List<SprocParameter>();
paramsSQL.Add(new SprocParameter("ID", textBoxID.Text) );
DataSet ds = StoredProcedureExecute("get_ID", paramsSQL );
if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
textBoxID.Text = ds.Tables[0].Rows[0]["ID"].ToString();
textBoxName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
textBoxAddress.Text = ds.Tables[0].Rows[0]
["Address"].ToString();
textBoxPhone.Text = ds.Tables[0].Rows[0]["Phone"].ToString();
}
else
{
textBoxID.Text = "Unrecognised ID";
textBoxName.Text = "Incorrect Name";
textBoxAddress.Text = "Wrong Address";
textBoxPhone.Text = "Invalid Number";
}
}
You aim is not entirely clear here, as you appear to be asking how to handle multiple rows but assigning these values to a text box which would suggest you only actually want one at a time. May I suggest executing the command stored procedure is a more readable way:
DataSet ds = new DataSet("peopleData");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("get_ID", conn);
sqlComm.Parameters.AddWithValue("#ID", textBoxID.Text);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
Then the data can be accessed with something like this for a single row outputting to a textbox:
DataRow dr = ds.Tables[0].Rows[0]; // This will access the first row
textBoxName.Text = dr["Name"].ToString();
Or if you are expecting your stored procedure to return many rows, you can iterate through them by doing something like the below. Although, in this case I suspect you wouldn't want to assign each value directly to the textbox, so it may be more appropriate deploy a ListView as suggested in the comments.:
foreach (DataTable dt in ds.Tables) // Only if you're expecting many datatables.
{
foreach (DataRow dr in dt.Rows)
{
textBoxName.Text = dr["Name"].ToString();
}
}

Retrieve data and display into multiple controls with loop , c# asp.net

net sql server , I want a loop to retrieve data from sql database to different label controls using C# asp.net sql server storedprocedure.
string constrng = ConfigurationManager.ConnectionStrings["baby"].ConnectionString;
SqlConnection conn = new SqlConnection(constrng);
SqlCommand sqlComm;
sqlComm = new SqlCommand("stor_proc", conn);
sqlComm.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
DataSet ds = new DataSet();
ds.Tables.Add("Home");
ds.Tables[0].Load(dr);
m.Text = ds.Tables[0].Rows[0][1].ToString();
i.Text = ds.Tables[0].Rows[0][2].ToString();
d.Text = ds.Tables[0].Rows[0][3].ToString();
g.Text = ds.Tables[0].Rows[0][4].ToString();
m1.Text = ds.Tables[0].Rows[1][1].ToString();
i1.Text = ds.Tables[0].Rows[1][2].ToString();
d1.Text = ds.Tables[0].Rows[1][3].ToString();
g1.Text = ds.Tables[0].Rows[1][4].ToString();
m2.Text = ds.Tables[0].Rows[2][1].ToString();
i2.Text = ds.Tables[0].Rows[2][2].ToString();
d2.Text = ds.Tables[0].Rows[2][3].ToString();
g2.Text = ds.Tables[0].Rows[2][4].ToString();
conn.Close();
for (int i = 0; i < 3; i++ ) {
m.Text = ds.Tables[0].Rows[i][1].ToString();
i.Text = ds.Tables[0].Rows[i][2].ToString();
d.Text = ds.Tables[0].Rows[i][3].ToString();
g.Text = ds.Tables[0].Rows[i][4].ToString();
}
You can use a foreach loop like this:
foreach (DataRow row in ds.Tables[0].Rows)
{
// Now here, you are iterating through a individual row.
// ItemArray gives an index position of a cell within a row.
m.Text = row.ItemArray[0].ToString();
i.Text = row.ItemArray[1].ToString();
d.Text = row.ItemArray[2].ToString();
g.Text = row.ItemArray[3].ToString();
}

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";

Categories

Resources