How to add items in a datatable to a listview? - c#

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
}

Related

Binding data from SQL Table to custom list created using user control in C#

I am working a project and i need to display on a form (frmCaterlogs) a list of items. I have successfully implimented a custom list using a user control & FlowLayOutPanel. However now i am stuck on how i can bind my caterlogs that sits on a sql database to my custom list: Here is my code. on the custome_list(CatList), i have 4 controls, Id, Titile, Description, Icon stored in database as binarydata in the sqldb. I am lost on how i can bind data to the custom list control that can look thought all the records in my database. Thanking you all in advace for your kind advices.
private void PopulateCatelog()// This code is triggered when frmcaterlogs loads.
{
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ListView Items = new ListView()
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows) // This is where i am stuck
{
CatList iList = new CatList(dr["Item"].ToString());
iList.Title = dr;
}
CatList[] ListItem = new CatList[l];
//Loop though to check each item
for (int i = 0; i < ListItem.Length; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = fetch data for a list;
ListItem[i].Message = "fetch data for a lis";
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
I got the desired result after altering the code as seen below
private void FrmCatalogs_Load(object sender, EventArgs e)
{
PopulateCatelog();
}
private void PopulateCatelog()
{
//Populate your listitem here
int l;
string query = "SELECT * from ServicesCaterlogs";
SqlConnection con = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
l = dt.Rows.Count;
foreach(DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["Item"].ToString());
ListViewItem des = new ListViewItem(dr["Item_Description"].ToString());
CatList[] ListItem = new CatList[l];
for (int i = 0; i < ListItem.Length - l +1 ; i++)
{
ListItem[i] = new CatList();
ListItem[i].Title = item.Text;
ListItem[i].Message = des.Text;
ListItem[i].icon = Resources.Warning;
ListItem[i].IconBackground1 = Color.DarkGoldenrod;
if (FlowLayoutPanel.Controls.Count < 0)
{
FlowLayoutPanel.Controls.Clear();
}
else
{
FlowLayoutPanel.Controls.Add(ListItem[i]);
}
}
}
}

How can add datatable items to list?

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]));

C# System.Data.DataRowView

I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}

Subitems and Column names in ListView not displayed

This is the code I'm working on
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from sometable", con);
con.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
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["Col1"].ToString()); // Value is 9999
listitem.SubItems.Add(dr["Col2"].ToString()); // Value is 10
listitem.SubItems.Add(dr["Col3"].ToString()); // Value is 5
listView1.Items.Add(listitem);
}
}
But the output that I'm getting is of the order
Adding listView1.View = View.Details; to the code produces empty listview. How do I get an output that displays the column name and all values ?I'm oblivious to the mistake I'm doing. Any idea where I'm going wrong ?
Try settings listView1.View to View.Details and add 3 proper columns to listView1.Columns in designer:
or in code:
listView.Columns.Clear();
listView.Columns.Add("Col1");
listView.Columns.Add("Col2");
listView.Columns.Add("Col3");
Then, add items this way:
listView.Items.Add(new ListViewItem(new[]
{
dr["Col1"].ToString(),
dr["Col2"].ToString(),
dr["Col3"].ToString()
}));
It always works for me.
Your code may have produced an empty grid because you had no columns.

Retrieving selected checkedlistbox

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.

Categories