I have a Combobox in my form. This Combobox is populated with values from a table(Faculty) in the database.
I need to set the SelectedValue of this Combobox based on the record in another table(student). Both tables are in the same database.
I tried to set SelectedValue using the value getting from student table
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
but it didn't work.
So far I was only able to populate the Combobox ,
// --- populate faculty cmb ---
MySqlCommand cmdCmb = new MySqlCommand("SELECT facultyname FROM faculty;", db.getConnection());
db.openConnection(); // open connection
using (var reader = cmdCmb.ExecuteReader())
{
while (reader.Read())
{
cmbfaculty.Items.Add(reader.GetString("facultyname"));
}
}
but unable to set SelectedValue.
string sQuery = "SELECT indexno,faculty FROM student WHERE indexno ='"+selected+"'";
MySqlCommand cmd = new MySqlCommand(sQuery, db.getConnection());
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
txtindex.Text = table.Rows[0][0].ToString();
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
Hoping to fix the issue.
EDIT:
Able to do that by finding the item that exactly matches the specified
string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
Are there any other ways to archieve this.
Able to do that by finding the item that exactly matches the specified string ComboBox.FindStringExact Method,
cmbfaculty.SelectedValue = table.Rows[0][1].ToString();
needed to be replaced with
cmbfaculty.SelectedIndex = cmbfaculty.FindStringExact(table.Rows[0][1].ToString()) ;
Related
I am trying to list multiple companies in a combobox. These companies populate from database table tbl_companies. Combobox value should be id of table(Which is primary key of the table). Text should be the name of company.
Like id=1 and name = "XYZ".
Code is
string connStr = "My Connection string";
SqlConnection conn = new SqlConnection(connStr);
string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
SqlCommand cmd = new SqlCommand(strQuery, conn);
conn.Open();
SqlDataReader companyRead = cmd.ExecuteReader();
if (companyRead.HasRows)
{
while (companyRead.Read())
{
int cId = (Convert.ToInt16(companyRead["id"].ToString()));
cmbCompany.Items.Insert(cId, companyRead["name"].ToString());
}
}
conn.Close();
When I am executing the code, getting the following error.
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '1' is not valid for 'index'.
Parameter name: index'
For reference, I am also sharing the [enter image description here]screenshot of code with error1
I need guidance, how to fix the problem.
Your error is in the Item.Insert method where the first parameter should be the position in the already existing items collection where you want to insert the new value and not the Item's value.
Instead of using this manual loop you could simply set the combo datasource to a DataTable and set the DisplayMember and ValueMember properties
string connStr = "My Connection string";
using(SqlConnection conn = new SqlConnection(connStr))
{
string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
SqlCommand cmd = new SqlCommand(strQuery, conn);
conn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader())
cmbCompany.DisplayMember = "name";
cmbCompany.ValueMember = "id";
cmbCompany.DataSource = dt;
}
Consider also that once you set the Datasource property in this way you shouldn't manually insert new items, instead you add elements to the underlying DataTable and refresh the combo datasource binding
You are inserting at a specific index, and when the list is empty at the start, an index of '1' is considered out of range.
Try:
cmbCompany.Items.Add(companyRead["name"].ToString());
instead.
I have been working on a personal project for the company I work for to control stock levels in order to practice my c#.
I want my application to search through tblJuiceStock, find a matching FlavourID to what the user is inputting and update the stock of that record through an UPDATE SET query.
public void InsertJuiceStockWithCheck()
{
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
string tblJuiceStockCheck = "SELECT FlavourID, Quantity FROM tblJuiceStock";
OleDbCommand cmdCheck = new OleDbCommand(tblJuiceStockCheck, conn);
OleDbDataAdapter daCheck = new OleDbDataAdapter(cmdCheck);
DataTable dtCheck = new DataTable();
daCheck.Fill(dtCheck);
foreach (DataRow row in dtCheck.Rows)
{
if ((int)row["FlavourID"] == fID)
{
int currentQty = (int)row["Quantity"];
int updatedQty = currentQty + qty;
string tblJuiceStockExisting = #"UPDATE tblJuiceStock
SET Quantity = #newquantity
WHERE FlavourID = #flavourID";
OleDbCommand cmdJuiceStockExisting = new OleDbCommand(tblJuiceStockExisting, conn);
cmdJuiceStockExisting.Parameters.AddWithValue("#flavourID", fID);
cmdJuiceStockExisting.Parameters.AddWithValue("#newquantity", updatedQty);
cmdJuiceStockExisting.ExecuteNonQuery();
matchFound = true;
break;
}
}
if (!matchFound)
{
string tblJuiceStockNew = "INSERT INTO tblJuiceStock (FlavourID, Quantity, MinStockPOS) VALUES (#fID, #quantity, #minstock)";
OleDbCommand cmdJuiceStockNew = new OleDbCommand(tblJuiceStockNew, conn);
cmdJuiceStockNew.Parameters.AddWithValue("#fID", fID);
cmdJuiceStockNew.Parameters.AddWithValue("#quantity", qty);
cmdJuiceStockNew.Parameters.AddWithValue("#minstock", amt);
cmdJuiceStockNew.ExecuteNonQuery();
}
}
}
Please note: this query works fine in Access when I replace parameters with the same values. Also, using breakpoints I identified that the parameters have the correct values set to them, the variables assigned to them are obtained within another method, all methods are called in the submit button event.
However, the Quantity value in TblJuiceStock remains the same.
My tblJuiceStock table
After some time of messing about the answer was simple.
OLEDB does work with named parameters but you have to declare them, if you don't declare them they use the parameters positioning to match them up.
My problem was that in my query string I had #newquantity first and #flavourID second, whereas when adding my parameters I added #flavourID first and #newquantity second.
My checklist box is generated using a query
query = #"SELECT CONTENT
FROM qBank
GROUP BY CONTENT
ORDER BY MIN(CHAP)";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter dAdap = new OleDbDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdap.Fill(dSet);
for (int i=0; i < dSet.Tables[0].Rows.Count; i++)
{
chkList.Items.Add(dSet.Tables[0].Rows[i][0].ToString());
}
I want to get the values of the checkeditems query the CONTENT/s checked and pass it to the next form. But Im lost on how to do it. I saw using foreach statement, but honestly I cannot come up with the condition.
ListItem item = new ListItem();
item.Text = dSet.Tables[0].Rows[i][0].ToString(); //Text field here
item.Value = dSet.Tables[0].Rows[i][1].ToString(); //value field here
chkList.Items.Add(item);
Try to achieve this, hope you have different text and value fields, if you not have that use same thing into value and text field
Hi i am trying to get DropDownList to work with SqlDataReader but its not populating the DropDownlist. The TextBox.Text Reader is working though.
Here is the code I am using:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
{
SqlCommand command =
new SqlCommand("SELECT * FROM [datarep].[dbo].[OrderHeader] WHERE [OrderNumber] = '"+OrderNumber+"'", con);
con.Open();
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
TextBox2.Text = (read["CreatedDate"].ToString());
TextBox3.Text = (read["CreatedBy"].ToString());
CompanyStored = (read["CustomerID"].ToString());
TextBox7.Text = (read["Store_Number"].ToString());
DropDownList1.DataTextField = (read["Year"].ToString());
DropDownList1.DataBind();
}
read.Close();
}
Assuming your dropdown is already populated with the list of years, you need to set its value rather than setting its DataTextField - that property is meant for defining the column or property name of the data source for text, not setting the selected value itself.
DropDownList1.SelectedValue = read["Year"].ToString();
If you don't have the dropdown even populated yet, then you have to populate it in advance, using a data source, which is probably a list of years. For example, suppose you want all years between 2000 and 2050, something like this might do the trick:
var dataSource = Enumerable.Range(2000, 51)
.Select(x => new { TheYear = x })
.ToArray();
DropDownList1.DataSource = dataSource;
DropDownList1.DataValueField = "TheYear";
DropDownList1.DataTextField = "TheYear";
DropDownList1.DataBind();
Note that the DataTextField and DataValue field represent the property of the object in the data source.
For something simple like numbers, you can populate the dropdown one at a time as well, rather than using a data source - it's the same result in the end.
SqlDataReader reads your data line by line. If you want to use a DataReader you'll have to add a new list item to your DDL per iteration
Try it like this:
while (read.Read())
{
/*code omitted*/
var item = new ListItem();
item.Text = read["Year"].ToString();
item.Value = read["Year"].ToString();
DropDownList1.Items.Add(item);
}
Further reading and alternative solutions:
What is the right way to populate a DropDownList from a database?
Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.
Can anyone see why?
Code:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;
I always have to deal with this problem, even if I set the DisplayMember and ValueMembers of the List Box.
Your current code is correct and should work, if you need access to the current selected item value of any column of your dTable you can get them doing this:
DataRowView drv = (DataRowView)lstNames.SelectedItem;
String valueOfItem = drv["NameAndScore"].ToString();
What I like about getting the entire DataRowView is that if you have more columns you can still access their values and do whatever you need with them.
The following code should work:
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dSet.Tables[0];
If it does not work, please update your question and provide us with some information about the columns and values that are actually returned in dSet.Tables[0].
Set your lstNames.DisplayMember and lstNames.ValueMember fields.
Gets or sets the property to display for this ListControl.
Gets or sets the path of the property to use as the actual value for
the items in the ListControl.
This should solve your problem..
Like I said in the comments, please add lstNames.DataBind() to your code.
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
EDIT:
Can you try this instead:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
myConn .Open();
SqlCommand cmd = new SqlCommand(sqlStr, SQLConnection1);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lstNames.Items.Add(rd[0]);
}
rd.Close();
rd.Dispose();
myConn.Close();
If you want your list box to show values from an specific column of the data source use
lstNames.DataTextField = "SpecialColumnName";
I use :
foreach (DataGridViewRow row in _dataGridView.SelectedRows)
{
var rowObject = row.DataBoundItem as DataRowView;
var array = rowObject.Row.ItemArray;
}
Only the order of the calls is wrong. First set the DataSource and only after that set the display member:
lstNames.DataSource = dTable;
lstNames.DisplayMember = "NameAndScore";
I had the similar problem of picking a single value from a populated Listbox and getting System.Data.DataRowView.
I was able to solve it by casting the selected item to System.Data.DataRowView and then
accessing the Row and ItemArray subclasses:
var si = ListBox1.SelectedItem;
string val = ((System.Data.DataRowView)si).Row.ItemArray[0].ToString();
I know its an old question. Just thought it might be nice to add an update to the answers given already. I was looking for a solution to the same problem. I the realized it is in which order you place these 3 lines of code
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
It should use the datasource first. Then The value member and then the display member
As follow:
lstNames.DataSource = dTable;
lstNames.ValueMember = "NameAndScore";
lstNames.DisplayMember = "NameAndScore";
just make sure you are typing the name of field same as in datasource in other word it is a case sensitive
so :
Me.GridLookUpEdit1.Properties.DisplayMember = "cur_code"
is different than
Me.GridLookUpEdit1.Properties.DisplayMember = "CUR_code"
if you copied the object instead of placing as a new object it will do this. Try deleting the object and putting it back on. I had the same issue and this is what I did. Don't know why it worked, but it did.
Sometimes what might cause it is mis-spelt displaymember variable name.