I have a database with a table containing 3 columns. I would like to extract data from that table and add to a list.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand parancs = kapcsolat.CreateCommand();
parancs.CommandText = "select hossz from artandbihark";
kapcsolat.Open();
OleDbDataReader reader = parancs.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
List<double> tavolsag = new List<double>();
for (int i = 0; i < dt.Rows.Count; i++)
{
tavolsag.Add(Convert.ToDouble(dt.Rows[i]));
}
kapcsolat.Close();
}
But I cannot convert dt.Rows[i] to double. How can I finish the above code to add the data correctly?
You only have one property in your DataRow, so that's the 0th property.
tavolsag.Add(Convert.ToDouble(dt.Rows[i][0]));
Related
The following images show my two datagrid views
From what I understand from your question, you can use the following method
public DataTable numOfCalls(DataTable table)
{
//Initialize Result Table
DataTable numOfCallsTable = new DataTable();
numOfCallsTable.Columns.Add("agentName", typeof(string));
numOfCallsTable.Columns.Add("numOfCall", typeof(int));
// Get the unique agents
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "agentName");
// Check if there are agents
if (distinctValues.Rows.Count > 0)
{
// Loop thru the agents
for (int i = 0; i < distinctValues.Rows.Count; i++)
{
string agentName = distinctValues.Rows[i]["agentName"].ToString();
// Get all the rows that this agent has
DataRow[] agentRows = table.Select($"agentName='{agentName}'");
// And then fill the second table
DataRow newRow = numOfCallsTable.NewRow();
newRow["agentName"] = agentName;
newRow["numOfCall"] = agentRows.Length;
numOfCallsTable.Rows.Add(newRow);
}
}
return numOfCallsTable;
}
You can call this method every time you add or delete a line to the first table.
update for the button that you asked
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
dataGridView2.DataSource = numOfCalls(dt);
}
I've created a multicolumn list (lstItems) that I want to use for lookups so I don't have to do repeated data queries and I can't figure out how to reference the items/cells. If an alternate structure would be better/easier, I'm open to suggestions, but this is what I've got so far.
I can query the OLEDB table and populate lstItems but not sure how to reference the elements/cells. As a test I populated listbox1 from the query. Then after building lstItems I echoed back the contents, no problem. Now I need to do two things.
Populate listbox1 with one of the columns from lstItems instead of directly from the query.
Later, be able to query lstItems so when "nameValue" = the second column nameValue, return the corresponding ID.
.
sqlCmd.CommandText = "select ID, Name from table;
OleDbDataReader sqlRead = sqlCmd.ExecuteReader();
// Create a Name/Value list
List<KeyValuePair<string, string>> lstItems = new List<KeyValuePair<string, string>>();
int j = 0;
while (sqlRead.Read())
{
//Populate listbox1 directly from query
string nm= Convert.ToString(sqlRead["Name"]);
listBox1.Items.Add(nm);
// Create the multicolumn list
lstItems.Add(new KeyValuePair<string, string>
(Convert.ToString(sqlRead["ID"]), Convert.ToString(sqlRead["Name"])));
// Echo out to insure the list has the proper values
MessageBox.Show("Show List: " +lstItems [j].ToString());
j++;
}
I like to use DataTables for this sort of thing personally. I will then reference the table instead of the database when I need the data for lookups:
sqlRead = sqlCmd.ExecuteReader();
var dt = new DataTable();
for (var i = 0; i < sqlRead.FieldCount; i++)
{
dt.Columns.Add(sqlRead.GetName(i), typeof(string));
}
while (sqlRead.Read())
{
var row = dt.Rows.Add();
for (var i = 0; sqlRead.FieldCount; i++)
{
var val = sqlRead[i].ToString();
row[i] = val;
}
}
sqlRead.Close();
OR:
// Connection object is the second parameter
using (var a = new SqlDataAdapter("select ID, Name from table", c))
{
var t = new DataTable();
a.Fill(t);
}
Then you can reference the DataTable for data!
Example binding for winforms
private void Form1_Load(object sender, EventArgs e)
{
DataTable oDataTable = new DataTable();
using (SqlConnection oSqlConnection = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
using (SqlCommand oSqlCommand = new SqlCommand("select ProductID, ProductName from Product", oSqlConnection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(oSqlCommand))
{
adapter.Fill(oDataTable);
}
}
}
listBox1.DisplayMember = "ProductName";
listBox1.ValueMember = "ProductID";
listBox1.DataSource = oDataTable;
}
private void button1_Click(object sender, EventArgs e)
{
DataRowView selectedRow = (DataRowView)listBox1.SelectedItem;
MessageBox.Show(selectedRow["ProductId"].ToString());
}
I'm still learning C# and winform and I can't seem to find a fix to my problem. The problem is whenever I select items in my sql generated checkedlistbox and press the button2 event it won't show the actual data, it just shows "System.Data.DataRowView" am I missing something here is the code..
private void button2_Click(object sender, EventArgs e)
{
int counter = checkedListBox1.SelectedItems.Count;
List<string> selecteditems = new List<string>();
for (int i = 0; i < counter; i++)
{
selecteditems.Add(checkedListBox1.SelectedItems[i].ToString());
}
MessageBox.Show(selecteditems[0]);
for the generation of checkedlistbox here is the code.
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tbl_members ORDER BY Position", con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
DataSet ds = new DataSet();
adapter.Fill(ds);
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.Enabled = true;
checkedListBox1.Refresh();
count = Convert.ToInt32(numericUpDown1.Value);
con.Close();
Try replace your for loop in button2_Click to this:
foreach (DataRowView rowView in checkedListBox1.CheckedItems)
{
selecteditems.Add(rowView["FullName"].ToString());
}
there is both
MessageBox.Show(checkedListBox1.CheckedItems[0].ToString());
and
MessageBox.Show(checkedListBox1.SelectedItems[0].ToString());
use them according to your need I think you were looking for first one
Try using Convert.ToString(checkedListBox1.SelectedItems[i]) instead of .ToString()
.ToString() generally returns variable's class name in string if `.ToString()' not overrided by class.
I am currently developing a C# Windows Form Application.
Now I am trying to use a SQL Command to retrieve information from the database to fill in the information that I need to have in my Application.
A sample query would be "select * from Location"
In the Location table there would be variables like locationId, LocationName , districId etc etc.
I used the following code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem =new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
The output is:
but it should be like this:
you have to change some code
private void button1_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
SqlConnection con = new SqlConnection("connectionstring");
SqlDataAdapter ada = new SqlDataAdapter("select * from MasterLocation", con);
DataTable dt = new DataTable();
ada.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem listitem = new ListViewItem(dr["pk_Location_ID"].ToString());
listitem.SubItems.Add(dr["var_Location_Name"].ToString());
listitem.SubItems.Add(dr["fk_int_District_ID"].ToString());
listitem.SubItems.Add(dr["fk_int_Company_ID"].ToString());
listView1.Items.Add(listitem);
}
Added the following code
listView1.View = View.Details;
and it worked.
private void FormView_Load(object sender, EventArgs e)
{
sample = new DataTable(); //Sample Data
sample.Columns.Add("id", typeof(string));
sample.Columns.Add("name", typeof(string));
sample.Rows.Add("1", "apple");
sample.Rows.Add("2", "acer");
sample.Rows.Add("3", "alpha");
sample.Rows.Add("4", "beat");
sample.Rows.Add("5", "ball");
sample.Rows.Add("6", "cat");
sample.Rows.Add("7", "catch");
sample.Rows.Add("10", "zebra");
listViewEx1.View = View.Details;
listViewEx1.Columns.Add("id");
listViewEx1.Columns.Add("name");
}
listViewEx1.Items.Clear();
listViewEx1.FullRowSelect = true;
foreach (DataRow row in sample.Rows)
{
ListViewItem item = new ListViewItem(row["id"].ToString());
item.SubItems.Add(row["name"].ToString());
listViewEx1.Items.Add(item); //Add this row to the ListView
}
I want to fetch data from access database in a list view in C#...
This is what I'm using :
private void LstVwBrandNmO_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select BrandName from Inventory";
OleDbDataAdapter da = new OleDbDataAdapter(sql, bookConn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
What to do next?
after fetching the data in datatable just assign the datasource property of Listiew like this
ListView.DataSource = dt
and use databind function to bind the datasource to the list
ListView.DataBind();
before this make sure you have define Itemtemplate with <%#EVAL#> to bind the values in the datasource
You can also do a loop to add data to list like:
for (int i = 0; i < dt.Rows.Count; i++)
listBox1.Items.Add(dt.Rows[i][1]);
If you have already defined the columns and view in your ListView, you may simply set the ListView's ItemsSource to DataTable:
listView.ItemsSource = dt.DefaultView;
If you wanna do it programmatically, then this may help:
foreach (DataRow dataRow in dt.Rows) {
ListViewItem item = new ListViewItem(dataRow[0].ToString());
for (int i = 1; i < dt.Columns.Count; i++) {
item.SubItems.Add(dataRow[i].ToString());
}
listView.Items.Add(item);
}