I fill one combobox with two columns from database with this code:
foreach (DataRow dr2 in dt2.Rows)
{
comboBox1.Items.Add(dr2["Station"].ToString() + " - " + dr2["Ime"].ToString());
}
dbconn.Close();
and combobox look like this:
Now I want to take only first item from this combobox (the numbers) and put into my query for data from database.
I want variable Stations to be with first item from combobox.
I try to get the first index from combobox, but when I debug I see value on the variable is -1 everytime..
The code:
var Stations = comboBox1.SelectedIndex = -1;
MySqlCommand cmd = new MySqlCommand("CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('"+ dtnow +"', " + Stations + ", 5)", dbconn);
MySqlDataAdapter da = new MySqlDataAdapter();
dbconn.Open();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
dataGridView1.DataSource = dt;
}
dbconn.Close();
I upload a picture from debug mode:
I want variable Stations to be with first item from combobox
Instead of
var stations = comboBox1.SelectedIndex = -1;
use
comboBox1.SelectedIndex = -1;
var stations = comboBox1.SelectedText; // or Text
Related
I am trying to insert a non specific number of rows from a dataset into a list by using a foreach. But I am unsure how to add a non specific number of items to a list from a dataset.
public void DeviceReset(string r)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"SELECT installation_id FROM masterinstallationmaps WHERE masterinstallation_id = '" + r + "' ";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
I am picking out the installation_id from my masterinstallationmap table and if it contains more than 0 rows it should run the foreach to put the rows into the list, otherwise it should run a foreach only inputting 1 item to the list.
List<int> instIdList = new List<int>();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
//How to insert all rows from the dataset?
}
}
else
{
instIdList.Add(1);
}
The else statement works fine, but nothing happens if the Dataset have more than 0 rows.
I am unsure what to put into the foreach:
foreach (DataRow row in ds.Tables[0].Rows)
{
//How to insert all rows from the dataset?
}
Why can't you just add the value like
foreach (DataRow row in ds.Tables[0].Rows)
{
instIdList.Add(Convert.ToInt32(row["installation_id"]));
}
How to use loop to read all records by one click on the button. I have to print many reports.For each row in the table I need to create a report. And read until the last row of the table . My idea is using loop or index table but i don't know how to do it. This is my code:
private void btnin_Click(object sender, RoutedEventArgs e)
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdata1 WHERE Customers = '" + cbbcustomer.Text + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cnn.Close();
XtraReport1 report = new XtraReport1();
report.DataSource = dt;
report.ShowPreviewDialog();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
}
You could iterate through the Datatable
foreach(DataRow row in dt.Rows)
{
DataTable dtrow = new DataTable();
dtrow = dt.Clone();
dtrow.ImportRow(row);
XtraReport1 report = new XtraReport1();
report.DataSource = dtrow;
//report.ShowPreviewDialog(); Not sure what happens here but maybe a print method is better suited?
}
Basically for each row you create a datatable with the same structure and import one row. Then its assigned as your datasource. This will iterate through all rows.
For some reasons, I had to change something in my code. I used Mark Vance's code but it didn't work:
DataTable a = new DataTable();
a = ((DataView)ctrlgridviewdulieu0.ItemsSource).ToTable();
foreach (DataRow row in a.Rows)
{
DataTable dtrow = new DataTable();
dtrow = a.Clone();
dtrow.ImportRow(row);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdulieu2 WHERE Khachdat = N'" + dtrow.ToString() + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
XtraReport1 report = new XtraReport1();
report.DataSource = dt1;
// report.Print();
cnn.Close();
report.ShowPreviewDialog();
}
catch (Exception ex)
{
cnn.Close();
MessageBox.Show(ex.Message);
}
}
I have a dropdownlist that fills like:
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
Now I want to read the listing number of the selected item(in order to place it in a query).
So, while my dropdownlist has values like "Oxford University", "MIT University", "Simon Fraser University" etc, I want clicking an item from the list, store the value of this item in the list. To be more specific, if clicking the first item, then
int number = 1. if clicking the second item, then
int number = 2.
Is it possible to be done with something like:
DropDownList1.SelectedItem.????;
Thank you for your time!
You didn't bind item's value to dropdownlist, so you need to bind it.
like this
DropDownList1.DataValueField = ds.Tables[0].Columns["Column name that contain the value of Item"].ToString();
and then you can use to get it's value like as follow
string item_value = DropDownList1.SelectedValue;
If you want selected Value then use
DropDownList1.SelectedValue
and if you want selected item then use
DropDownList1.SelectedItem
In addition to Nitin Kumar answer, selected item text can be obtained by:
var selectedText = DropDownList1.SelectedItem.Text;
Selected Value
var selectedValue = DropDownList1.SelectedValue;
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns["SomeValueColumn or id column"];
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
and then you can use...
string id = DropDownList1.SelectedValue.ToString();
Try this.
cmd.CommandText = "select id,schoolName from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt );
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlPosition.DataSource = dt;
ddlPosition.DataTextField = "schoolName";
ddlPosition.DataValueField = "Id";
ddlPosition.DataBind();
}
}
I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
show_products.ItemsSource = dt5.DefaultView;
}
this code show one by one rows in datagridview
but i want to show all the product rows having categories_id in datagridview in one go
this is the function FillDataGridfromTree in databasecore class and its object is db
public DataTable FillDataGridfromTree(int product_Id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products.product_id as ID, products.remote_products_id as Remote_ID, products_description.products_name as name,products.products_model as model,products.manufacturers_id as manufacturersId,products.products_image as Image,products.products_price as Price,products.products_weight as Weight,products.products_date_added as dateAdded,products.products_last_modified as lastModified,products.products_date_available as dateAvailable,products.products_status as status,products.products_tax_class_id as taxClass FROM products INNER JOIN products_description ON products.product_id=products_description.products_id where products_description.language_id=1 and products_description.products_id=" + product_Id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable("products");
adapter.Fill(dt);
//show_products.ItemsSource = dt.DefaultView;
return dt;
}
}
this is the function through which i get product_id
public DataTable getProductIdFromCategoriesId(int categories_id)
{
string CmdString = string.Empty;
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
CmdString = "SELECT products_id FROM products_to_categories where categories_id=" + categories_id;
SqlCeCommand cmd = new SqlCeCommand(CmdString, con);
DataTable dt = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd);
adapter.Fill(dt);
return dt;
}
}
how to show all the rows instead of one row in datagridview
CHANGED Try changing your foreach loop to:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
DataTable dt5 = new Datatable();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
dt5.Merge(db.FillDataGridfromTree(int.Parse(products_id)));
}
show_products.ItemsSource = dt5.DefaultView;
You code is always going to display the last row for a category_id, this is because you're assigning an ItemsSource inside a loop. I've changed the top part to do what you looking for:
DataTable dt = db.getProductIdFromCategoriesId(categories_id);
List<DataRow> ProductList = new List<DataRow>();
foreach (DataRow row in dt.Rows)
{
string products_id = row["products_id"].ToString();
DataTable dt5 = db.FillDataGridfromTree(int.Parse(products_id));
if(dt5.Rows.Count > 0)
{
ProductList.AddRange(dt5.Select().ToList());
}
}
show_products.ItemsSource = ProductList.CopyToDataTable().DefaultView;