I wanna show my rows in a listbox and the table names but when i run my code it says System.Data.DataRow can someone help me
my code is
foreach (object SelectedValue in ListEmployees.SelectedItems)
{
using (connection = new SqlConnection(connectionstring))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM " + selectedCel, connection))
{
DataTable employees = new DataTable();
adapter.Fill(employees);
for (int i = 0; i < employees.Rows.Count; i++)
{
DataRow dr = employees.Rows[i];
ListViewItem itm = ListViewItem(dr.ToString());
listView1.Items.Add(itm);
}
}
}
DataRow.ToString() just prints out the full type name.
Presuming you want to show the first column:
ListViewItem itm = new ListViewItem(dr.Field<string>(0));
i wanna show all columns that are in the table
string[] allColumns = dr.ItemArray.Select(obj => obj.ToString()).ToArray();
ListViewItem itm = new ListViewItem(allColumns);
Related
I have a DataGridView and I want to fill it with two different arrays. With my current code, I can only add one column to the DataGridView. If I try to add two arrays only the last one is displayed on the DataGridView.
DataTable info= new DataTable();
SqlDataAdapter db = new SqlDataAdapter(query, con);
db.Fill(info);
if (info.Rows.Count > 0)
{
string prods= info.Rows[0]["prods"].ToString();
string prices= info.Rows[0]["prices"].ToString();
string[] f1 = prods.Split(',');
string[] f2 = prices.Split(',');
dataGridView2.AutoGenerateColumns = true;
dataGridView2.DataSource = f1.Select(x => new { prods= x }).ToList();
dataGridView2.DataSource = f2.Select(y => new { prices= z }).ToList();
}
So why not just add the products as the datasource and then add a column for price which you can then populate:
dataGridView2.Columns.Add(new DataColumn("Prices", typeof(string)));
int i = 0;
foreach (string row in prods){
dataGridView2["Prices][i] = row;
i++;
}
I read this question: BackgroundWorker to read database and update GUI
And thinks, that this is a good way to solve this problem.
The only thing is, that I create my Columns dynamically.
I read schemaInfo from DataBase to get the ColumnNames and create a DataGridColumn foreach Column in DataBase.
Now i want to do this with a BackgroundWorker, but u can't update the UI with a BackgroundWorker.
For now (without BackgroundWorker) I have 2 Methods to get the DataBase values.
To load the columns:
using (MySqlDataReader reader = cmd.ExecuteReader())
{
using (DataTable schema = reader.GetSchemaTable())
{
foreach (DataRow col in schema.Rows)
{
DataGridTextColumn column = new DataGridTextColumn();
string columnstring = col.Field<String>("ColumnName");
comboFilter.Items.Add(UppercaseFirst(columnstring));
column.Binding = new Binding(col.Field<String>("ColumnName"));
column.Header = UppercaseFirst(col.Field<String>("ColumnName"));
column.IsReadOnly = true;
Style textStyle = new Style(typeof(TextBlock));
textStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));
column.ElementStyle = textStyle;
dataGridPrivatecustomers.Columns.Add(column);
}
}
}
To load values
using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(string.Format("SELECT * FROM {0}", privateCustomerTablename), connection))
{
using (DataTable dt = new DataTable())
{
dataAdapter.Fill(dt);
dataGridPrivatecustomers.ItemsSource = dt.DefaultView;
}
}
So I tried to make both in one and struggled at creating the result List for the DataGrad's ItemSource:
using (MySqlDataReader reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
using (DataTable schema = reader.GetSchemaTable())
{
foreach (DataRow row in schema.Rows)
{
results.Add(new
{
});
i++;
}
}
}
}
The thing is, that I need to know how I can put the ColumnName + Value in the result List.
In the linked question he did
Id = rdr.GetInt32(0),
But i can't do row.Field<String>("ColumnName") = reader[i].ToString()
The code also don't know how much Columns to add so i guess i need another for or foreach loop ? And how I can set the ColumnName ?
I think that some people want to know this too because (for me) it looks really tricky for beginning Developers who wan't Columns and Values from DataBase to show in a DataGrid with a BackgroundWorker.
So i will show you, how I solved my question.
First I created a List to store all ColumnNames.
private List<string> columnList = new List<string>();
After that I edited the worker_DoWork Event as follows:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(conf.connection_string))
{
if (OpenConnection(connection))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = string.Format("SELECT * FROM {0}", privateCustomerTablename);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
using (DataTable schemaTable = reader.GetSchemaTable())
{
columnList.Clear();
foreach (DataRow row in schemaTable.Rows)
{
columnList.Add(row.Field<String>("ColumnName"));
}
}
}
using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd.CommandText, connection))
{
using (DataTable dt = new DataTable())
{
dataAdapter.Fill(dt);
e.Result = dt;
}
}
}
connection.Close();
}
}
}
First you can see i made a DataReader to read the DataBase schema and store it in a DataTable so I can loop it trough a foreach loop. In this Loop I add each Item from the schemaTable to my List so the List contains all ColumnNames of the selected DataBase Table.
After that I created a DataAdapter and store the content to another DataTable. And i pass this DataTable via e.Result = dt to the worker_RunWorkerCompleted Event. Now I want to access this data in my worker_RunWorkerCompleted Event.
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
foreach (var item in columnList)
{
DataGridTextColumn column = new DataGridTextColumn();
column.Binding = new Binding(item);
column.Header = UppercaseFirst(item);
column.IsReadOnly = true;
dataGridPrivatecustomers.Columns.Add(column);
}
DataTable dt = e.Result as DataTable;
dataGridPrivatecustomers.ItemsSource = dt.DefaultView;
}
I loop all items in my columnList and create a DataGridTextColumn for each item in this list and add it to my DataGrid.
After that all Columns are added into my DataGrid and I set the ItemsSource of my DataGrid to the DataTable i passed from worker_DoWork to worker_RunWorkerCompleted.
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();
}
I extract data from all sheets in a workbook using the following code :
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
if (sheetName.Contains("_"))
{
}
else
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
var dataTable = new DataTable();
string query = string.Format("SELECT * ,{0} as sheetName FROM [{0}]", sheetName);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
try
{
adapter.Fill(dataTable);
ds.Tables.Add(dataTable);
}
catch { }
}
}
I can't just figure how data are stocked in DataTable : sheetname is added as column ? how can I extract it ?
foreach (DataTable dt in ds.Tables)
{
using (SqlConnection con = new SqlConnection(consString))
{
con.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j ++)
{
//what should I write here ?
}
}
}
In order to get the sheet name, using oledb, you will need to use code that looks something like this (thanks to this SO post and answer):
DataTable dtSheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> sheets= new List<string>();
foreach (DataRow dr in dtSheets.Rows)
{
if (dr["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
sheets.Add(dr["TABLE_NAME"].ToString());
}
}
Below is how you access the values from a datatable:
var someValue = dt.Rows[i][j]
You need to get the item at the column index (j) of the row, at the row index (i), of the current datatable (dt).
Conversely, you can use the name of the column as well.
var someValue = dt.Rows[i]["columnName"]
assuming dt is your datatable variable,
do dt.Rows[row index][column index]
like
dt[2][4] -> will reference the 2nd row, 4th cell
I am not sure, but perhaps the sheetname might be stored at dt.TableName
I have a combobox on my form and a datatable. The combobox will be filled by some row values fro the datatable. But before that I would like to add a combobox item called (new) that will be the first option of the combobox in case the user would like to add a new item.
But when my combobox is filled, my (new) does not show up for some reason.
string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
ComboboxItem item = new ComboboxItem()
{
Text = dtSmsMessages.Rows[i]["Name"].ToString(),
Value = dtSmsMessages.Rows[i]["Id"].ToString()
};
comboSMSMessages.Items.Add(item);
}
}
comboSMSMessages.SelectedIndex = 0;
comboSMSMessages.Items.Clear(); Clear all the items
Add comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
after you cleared the combobox Your code should be like
string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
ComboboxItem item = new ComboboxItem()
{
Text = dtSmsMessages.Rows[i]["Name"].ToString(),
Value = dtSmsMessages.Rows[i]["Id"].ToString()
};
comboSMSMessages.Items.Add(item);
}
}
comboSMSMessages.SelectedIndex = -1;