I would like to select a specific column from a Dataset once it's been populated (e.g. Column Grades) and put the values into a list
string excelFile = #"C:\Scores.xlsx";
if (File.Exists(excelFile))
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+excelFile+";Extended Properties=Excel 12.0;";
var dataAdapter = new OleDbDataAdapter();
var objConn = new OleDbConnection(connString);
//SELECT [Name],[Grade],[Location] ect...
const string query = "SELECT * FROM [TeamScores$]";
var objCmd = new OleDbCommand(query, objConn);
var table = new DataSet();
dataAdapter.SelectCommand = objCmd;
dataAdapter.Fill(table);
//I would like to filter the DataSet to select only [Name] and populate the values into a List<string>
dataGridView1.DataSource = table.Tables[0]; //Will show all results
}
Your variable naming is confusing you.
var table = new DataSet(); // not good at all
A DataSet is not a table. A DataSet contains DataTables.
Try:
DataSet ScoresDataSet = new DataSet();
Then you can use the Select method on the table (something like...):
DataTable ScoresTable = ScoresDataSet.Tables[0];
dataGridView1.DataSource = ScoresTable.Select("Your criteria");
I have now solved the issue I can change "Grade" to which ever column I wish and it'll show the values associated.
DataTable scoresTable = ScoresDataSet.Tables[0];
var result = scoresTable.AsEnumerable()
.Select(r => r.Field<string>("Grade")).Where(r => r != null);
var listOfGrades = result.ToList();
You need adjust this line:
dataGridView1.DataSource = table.Tables[0]; //Will show all results
for example this one:
dataGridView1.DataSource = table.Tables[0].Select("yourField=5")); // you filter the datarows where yourField is 5.
or
dataGridView1.DataSource = table.Tables[0].Select("yourField>5 and yourField<21")); // is another example
Hopefully this can help you :
System.Data.DataSet dsTemp2 = new System.Data.DataSet();
if (dsTemp2.Tables[0].Rows.Count <= 0)
MessageBox.Show("Records not found");
else
{
foreach (DataRow dRow in dsTemp2.Tables[0].Rows)
{
yourtextbox1.Text = dsTemp2.Tables[0].Rows[0][4].ToString();
yourtextbox2.Text = dsTemp2.Tables[0].Rows[0][5].ToString();
yourtextbox3.Text = dsTemp2.Tables[0].Rows[0][7].ToString();
}
}
Related
I have gridview and
GridViewName.DataSource = table;
table values:
string myConnection = ConfigurationManager.ConnectionStrings["vizitka"].ToString();
string Query_sel = MySqlString;
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase_sel = new MySqlCommand(Query_sel, conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase_sel;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
TableName.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I get Values:
then, I'm adding new row to table:
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
and getting values with empty cells (also ID is empty and it's good for me):
then:
GridViewName.DataSource = table;
all is good, but then if I want to delete from table this new created row, I cannot. I'm trying to filter and bind again GridViewName.
DataView view = new DataView(table);
view.RowFilter = "CONVERT(id, System.String) = null or CONVERT(id, System.String) = ''";
Console.WriteLine(view);
but I'm getting empty table. Why?
I assume the ID is numeric. You don't want = null, you want IS NULL, which is how you check for nulls in both DataView (and also in SQL).
view.RowFilter = "ID IS NULL";
I got values from a .csv file and put them into a datagridview, but I'd like to replace some values before to fill my datagridview.
This is the screen of my .csv file:
and this is my code to try to do it:
string FileName = #"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
DataTable dt = ds.Tables[0];
List<HT> matchhtList = new List<HT>();
matchhtList = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString(),
Away = dr["Away"].ToString(),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
Segno = dr["Segno"].ToString(),
odd1 = dr["odd1"].ToString(),
oddx = dr["oddx"].ToString(),
odd2 = dr["odd2"].ToString()
}).ToList();
StringBuilder mystring = new StringBuilder("matchhtList");
mystring = mystring.Replace("Rosenborg", "Rihanna")
.Replace("Start", "Stop")
.Replace("Brann", "Circus");
dataGridView2.DataSource = mystring;
Please, if my question is not clear, tell me before to put "-1", I'll try to explain better my question. Thank you very much!
you can replace the the text when you build the list
matchhtList = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString().Replace("Rosenborg", "Rihanna"),
Away = dr["Away"].ToString().Replace("Start", "Stop").Replace("Brann", "Circus"),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
Segno = dr["Segno"].ToString(),
odd1 = dr["odd1"].ToString(),
oddx = dr["oddx"].ToString(),
odd2 = dr["odd2"].ToString()
}).ToList();
dataGridView2.DataSource = matchhtList;
you can manipulate the values in rowdatabound event of gridview
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound(v=vs.110).aspx
And your datasource must be a List or DataTable in above scenario.
dataGridView2.DataSource = mystring;//Wrong
should be
dataGridView2.DataSource = matchList;
I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();
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;
I have a datagrid view in which I set value like this
string query = "select CustomerId,CustomerName from tbl_Customer where flag=0";
SqlDataAdapter daCustomer = new SqlDataAdapter(query, con);
daCustomer.Fill(ds, "Customer");
cmbCustomerName.DisplayMember = "CustomerName";
cmbCustomerName.ValueMember = "CustomerId";
cmbCustomerName.DataSource = ds.Tables["Customer"];
cmbCustomerName.ResetText();
but it gives me this error after this line
cmbCustomerName.DataSource = ds.Tables["Customer"];
when I set datasource. Please help me fix this.
Try this :
DataTable dt = new DataTable();
daCustomer.Fill(dt);
cmbCustomerName.DataSource = dt;