Reload all dropdownlist after I clear one dropdown in c# - c#

So, here it is my problem
I have four dropdowns in the screen, and all four are loaded when the screen loads, also when I change the first combobox, all three load with the selectedindex method, no problems in that.
But when I manually clear the first combobox, the remaining three retain the same values as before and I am not able to reset them. Any suggestions ?
private void comboBox_commodity_SelectedIndexChanged(object sender, EventArgs e)
{
//filter stat type
if (!comboBox_commodity.Text.Equals(""))
{
statTypes = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select [ERSStatisticType_Attribute] from " + schemaName + "ERSStatisticType_LU " +
"WHERE ERSStatisticType_ID IN (SELECT DISTINCT[ERSCommodity_ERSStatisticType_ID] FROM "
+ schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID
+ " and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
statTypes.Add(row["ERSStatisticType_Attribute"].ToString());
}
}
comboBox_statType.DataSource = statTypes;
comboBox_statType.SelectedItem = null;
//filter unit
//filter source
source = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select DISTINCT ERSSource_Desc from " + schemaName
+ "ERSSource_LU where ERSSource_ID IN (SELECT DISTINCT[ERSCommodity_ERSSource_ID] FROM " + schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID +
" and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ORDER BY ERSSource_Desc";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
source.Add(row["ERSSource_Desc"].ToString());
}
}
comboBox_source.DataSource = source;
comboBox_source.SelectedItem = null;
unit = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select distinct ERSUnit_Desc from " + schemaName
+ "ERSUnit_LU ulu" + "," + schemaName + "ERSCommodityDataSeries cds" + "," + schemaName + "ERSDataValues dv " +
" where ulu.ERSUnit_ID=dv.ERSDataValues_ERSUnit_ID " +
" and cds.ERSCommoditySubCommodity_ID= " + getCommodityID(comboBox_commodity.Text) +
" and cds.ERSCommodity_ID=dv.ERSDataValues_ERSCommodity_ID " +
" and [ERSCommodity_ERSGroup_ID] = " + groupID;
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
unit.Add(row["ERSUnit_Desc"].ToString());
}
}
comboBox1_unit.DataSource = unit;
comboBox1_unit.SelectedItem = null;
}
else
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}
If I manually clear the combobox, all other three values should be loaded with all the revelant values.

Now, I'm not 100% on your utilization here, but based off the initial issue I would use the Textupdate Event Handler like this:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
ClearCmboboxesOnFirstEmpty(comboBox_commodity.Text);
}
private void ClearCmboboxesOnFirstEmpty(string comboValue)
{
if(comboValue == "")
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}

Related

DataView Filter not finding match

I'm selecting a DataView row based on a Tag value from a treeview. It Works fine most of the time, but under certain conditions does not return a record. I wrote the code below to test each row before I call the filter.
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (treeView1.SelectedNode != null)
{
TreeNode tn = treeView1.SelectedNode;
Console.WriteLine(tn.Tag.ToString());
selectedTag = tn.Tag.ToString();
dv.Table = ds.Tables["ProductStruct"];
foreach (DataRow dr in dv.Table.Rows)
{
bool test = dr["uniqueID"].ToString() == tn.Tag.ToString();
Console.WriteLine(dr["uniqueID"].ToString() + " and " + tn.Tag.ToString() + test);
}
dv.RowFilter = "uniqueID = '" + tn.Tag.ToString() + "'";
Console.WriteLine(dv.RowFilter.ToString());
Console.WriteLine(dv.Count.ToString());
}
}
the output is as follows:
12331233-200-00e
12331233 and 12331233-200-00eFalse
12331233-100-000 and 12331233-200-00eFalse
12331233-200-00e and 12331233-200-00eTrue
12331233-300-000 and 12331233-200-00eFalse
12331233-400-000 and 12331233-200-00eFalse
12331233-500-000 and 12331233-200-00eFalse
12331233-600-000 and 12331233-200-00eFalse
12331233-700-000 and 12331233-200-00eFalse
12331233-800-000 and 12331233-200-00eFalse
12331233-900-000 and 12331233-200-00eFalse
uniqueID = '12331233-200-00e'
0
As you can see the bool test is true for one record but filter fails to return it. Any help is appreciated, I hate to use a loop where a single line should do the trick...
The loop you run overrides the value of the bool and loops as many times as the count of row exists in your table.
Inside the loop, use return to escape once you find the match. It will not go through all the rows. This will return only 1 value.
foreach (DataRow dr in dv.Table.Rows)
{
bool test = dr["uniqueID"].ToString() == tn.Tag.ToString();
if(dr["uniqueID"].ToString() == tn.Tag.ToString()){
Console.WriteLine(dr["uniqueID"].ToString() + " and " + tn.Tag.ToString() + test);
dv.RowFilter = "uniqueID = '" + tn.Tag.ToString() + "'";
return;
}
}
If you are expecting more matches, move the
dv.RowFilter = "uniqueID = '" + tn.Tag.ToString() + "'";
Inside the loop and encapsulate it with if statement.
foreach (DataRow dr in dv.Table.Rows)
{
bool test = dr["uniqueID"].ToString() == tn.Tag.ToString();
Console.WriteLine(dr["uniqueID"].ToString() + " and " + tn.Tag.ToString() + test);
if(dr["uniqueID"].ToString() == tn.Tag.ToString()){
dv.RowFilter = "uniqueID = '" + tn.Tag.ToString() + "'";
}
}
This will run the filter each time it finds a match.
I hope this helps.

How to insert multiple data into database?

i would like to insert multiple data into my database. I am using for-each statement to get the data and when i insert into the database, it generates 10(just a random no. depending on the no. of data i retrieved) rows for me with one data in every row instead of all in one row. here is the for-each statement i am using.
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + kiev.Key + " ) VALUES ( '" + kiev.Value + "' ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();
}
}
There are better options like "SqlBulkCopy" available as already mentioned in the comments but also something like this should work:
string tablename = "";
string values = "";
string keys = "";
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
keys += kiev.Key + ", ";
values += "'" + kiev.Value + "', ";
}
}
keys = keys.Remove(keys.Length - 2);
values = values.Remove(values.Length - 2);
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + keys + " ) VALUES ( " + values + " ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();

I want to edit the datagridview to Update Dataset directly to DB,but always failed

My Problem as follows;
Last row of datagridview is always Focused, so when I click the btnSave of toolStripButton, I can not save the last row data to the database. How should I solve this problem? I know if I use the Button Control, I can solve this problem. But I want to know more:
private void btnSave_Click(object sender, EventArgs e)
{
dgvHead.EndEdit();
dgvHead.RefreshEdit();
dgvHead.Refresh();
dgvHead.Update();
dgvHead.LostFocus += new EventHandler(dataGridView1_LostFocus);
//dgvHead.ClearSelection();
//int id = 0;
//保存到数据库之前先判断一下主表是否有重复记录
string fno = txtfNo.Text.Trim();
string fname = txtPname.Text.Trim();
int orderqty = Convert.ToInt32(txtOrderQty.Text);
double orderc = Convert.ToDouble(txtOrderCoefficient.Text);
Image pic = pbchef.Image;
//主表的修改
string sql1 = "select count(1) from desProductAttach where fno='" + fno + "' and fno!='" + args["pNo"].ToString() + "' and fname='" + fname + "' and orderqty=" + orderqty + " and orderCoefficient=" + orderc + "";
int count = Convert.ToInt32(SqlHelp.GetValue(CommandType.Text, sql1));
if (count != 0)
{
MessageBox.Show("数据库中已经存在重复记录,请修改后重新录入!");
return;
}
string sql2 = #"update desProductAttach set fno='" + fno + "',fname='" + fname + "',orderqty=" + orderqty + ",orderCoefficient=" + orderc + " where id="+id+"";
SqlHelp.ExecuteNonQuery(CommandType.Text,sql2);
//子表的更新(通过数据源更新)
if (ds1.HasChanges())
{
SqlCommandBuilder cb = new SqlCommandBuilder(sda1);
sda1.Update(ds1.Tables[0]);
ds1.AcceptChanges();
// dgvHead.Update();
MessageBox.Show("保存成功");
// ischange = false;
}
}

Get all items of listbox by converting it in string values

I have listbox and its items are the selected dates from Calendar control in ASP.net. Now I need to filter them in foreach loop according to whether every single date is present database table or not. And the code for same I used is like as:
foreach (string item in ListBoxSelectedDates.Items)
{
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
And getting error at first line of above code is:
Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to
type 'System.String'.
I am not getting proper solution after continuously trying...
foreach (var _iterator in ListBoxSelectedDates.Items) // here "lstDate" is name of your list where you store all date.
{
string item = _iterator.ToString();
string q = "select count(*) from event_calendar where _date='" + Convert.ToDateTime(item).ToString("yyyy-MM-dd") + "'";
MySqlCommand cmd = new MySqlCommand(q, conn);
conn.Open();
if ((long)(cmd.ExecuteScalar() ?? 0) == 0)
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Leave <br>";
i++;
}
else
{
strBody += i + ". " + Convert.ToDateTime(item).ToString("dd-MMM-yyyy") + ", " + Convert.ToDateTime(item).DayOfWeek + " : Holiday <br>";
i++;
}
conn.Close();
}
You can use the ListItem.ToString() Method to convert the ListItem to a String.
foreach (var _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.ToString();
//The rest of your logic here
conn.Close();
}
If you want to access explicitly the value, you can have a look to the ListItem documentation, there you can see that there is a public property called Value so you can use instead:
string item = _iterator.Value;
so you get:
foreach (ListItem _iterator in ListBoxSelectedDates.Items)
{
string item = _iterator.Value;
//The rest of your logic here
conn.Close();
}

Listview value to combobox

I have this combobox fetching values from SQL:
public void brandSelectCB(ComboBox cb)
{
string sSQL = " SELECT" +
" id, name" +
" FROM" +
" tbBrand" +
" ORDER BY" +
" name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
cb.DataSource = dt;
cb.DisplayMember = "name";
cb.ValueMember = "id";
}
I have also a listview like this:
public void modelSelect(ListView lvModel)
{
string sSQL = " SELECT" +
" tbModel.id, tbBrand.name AS brand, tbModel.name" +
" FROM" +
" tbBrand, tbModel" +
" WHERE" +
" tbBrand.id = tbModel.brand" +
" ORDER BY" +
" tbBrand.name, tbModel.name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["id"].ToString());
item.SubItems.Add(dr["brand"].ToString());
item.SubItems.Add(dr["name"].ToString());
lvModel.Items.Add(item);
}
}
When I select a row from the listview and click the edit button, it should get the values from that selected row to the corresponding comboboxes and textboxes:
private void btnEdit_Click(object sender, EventArgs e)
{
this.txtID.Text = lvModels.SelectedItems[0].SubItems[0].Text;
this.cbBrand.SelectedText = lvModels.SelectedItems[0].SubItems[1].Text;
this.txtName.Text = lvModels.SelectedItems[0].SubItems[2].Text;
}
but I get no values on the comboboxes, only in the textboxes. I realize that it is because the combo is in dropdownlist style, and i should use SelectedValue or SelectedItem but neither of them seems to work.
Any ideas ?
You might try something like this:
string brandText = lvModels.SelectedItems[0].SubItems[1].Text;
DataRow itemToSelect = ((DataTable) this.cbBrand.DataSource)
.Rows
.Cast<DataRow>()
.FirstOrDefault(r=>r.Field<string>("name").Equals(brandText));
if(itemToSelect != null)
cbBrand.SelectedItem = itemToSelect;
Disclaimer: I didn't test this out; this is from memory.
This would be simpler if you stashed the BrandID somewhere in the ListViewItem: then you could use SelectedValue.

Categories

Resources