Subitems and Column names in ListView not displayed - c#

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.

Related

Get Cell from a DataTable

I am working with DataTables. And I have one that is the following:
Ok, what I want to do is for example if I am in the level 1 (COSC-1218-SIT41SCH), I want to get the cell of "Cantidad" of level 2 in red. For example, the cells are C3, C4, C5, C6 and C7. How can I do this with datatables? with .Select or have to use loops? I am completely new with datatables.
First, you can try to get the row index of "COSC-1218-SIT41SCH". And then traverse the DataTable to get "Cantidad". Here is a simple demo you can refer to.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
// Define a list to store the row index of "COSC-1218-SIT41SCH"
List<int> list = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Connection String"))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From GetCellTest", conn);
sda.Fill(ds, "T_Class");
}
dt = ds.Tables["T_Class"];
foreach (DataRow dr in dt.Rows)
{
if (dr["Level1"].ToString() == "COSC-1218-SIT41SCH")
{
list.Add(dt.Rows.IndexOf(dr));
}
}
// Filter the first one
list.Remove(0);
// Get the value of "Cantidad"
foreach(var i in list)
{
Console.WriteLine(dt.Rows[i]["Cantidad"].ToString());
}
}

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.

getting value of combobox to textbox

using query i have called two columns value from database into one column. the point is now i want to select a value form combobox and put one column value into textbox.
e.g
two column values from database into combobox below
10001 haider <------ when i select this index i want only haider to be viewed into the textbox
10002 fahad
10003 aitazaz
the snippet which i have used for calling the two colums value from database is:
public void account()
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no, acc_name FROM accounts_record";
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbacc.Items.Add(ds.Tables[0].Rows[i][0] + " " + ds.Tables[0].Rows[i][1]);
}
con.Close();
}
You should be adding values and text to the combobox separately.
Here's an example ComboBox: Adding Text and Value to an Item (no Binding Source).
If you have to display the id in the text you have to do some parsing before putting the selected text into the textbox.
Use ComboBox.SelectedIndexChanged event of the combobox to populate the textbox accordingly. use http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindexchanged(v=vs.110).aspx
If you are able to get the 2 value text of the combo box on selection change then you can split it with space (" ") character and take the 2nd string and put it in textbox.
For example
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] splitedStr = comboBox1.SelectedText.Split(' ');
textBox1.Text = splitedStr[1];
}
You should use the code as below
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT acc_no +'-' + acc_name as AccNoWithName , acc_no as ActNo FROM accounts_record";
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dsn = new DataSet();
adpt.Fill(dsn);
con.Close();
comboBox1.DisplayMember = "AccNoWithName";
comboBox1.ValueMember = "ActNo";
comboBox1.DataSource = dsn.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = comboBox1.SelectedValue.ToString();
}

How to add items in a datatable to a listview?

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
}

combobox must be autocomplete and allow only seleted value from the list

I want a combo box functionality like -
The combo box shows items and has auto-complete functionality, as the list of items is very large.
I want the user to be able to select a value from the item list by typing into the box w/ the autocomplete functionality - if a user types something that's not in the list, then an available value is automatically selected.
I do not want to send the wrong text to the database.
This combo box is editable ,auto complete , but not accept the editable value ,user must select in list by typing ....
private void FrmGroupCreation_Load(object sender, EventArgs e)
{
string con = ConfigurationManager.ConnectionStrings["SaiCon"].ConnectionString;
using (SqlConnection connect=new SqlConnection(con))
{
//data table for combox type of account
SqlDataAdapter da = new SqlDataAdapter("SELECT *FROM dbo.Type_of_Account",connect);
DataTable dt=new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count ; i++)
{
cbTypeofAccount.Items.Add(dt.Rows[i]["type_Of_Acct"]);
}
//data table for combobox principle account type
SqlDataAdapter da1 = new SqlDataAdapter("SELECT *FROM dbo.Principle_Account", connect);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
for (int i = 0; i < dt1.Rows.Count; i++)
{
cbPrinciple_account_type.Items.Add(dt1.Rows[i]["Principle_Account"]);
}
//data table for combobox Under the group
SqlDataAdapter da2 = new SqlDataAdapter("SELECT *FROM dbo.Head_group_Account", connect);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
for (int i = 0; i < dt2.Rows.Count; i++)
{
cbUnder_the_group.Items.Add(dt2.Rows[i]["Account_name"]);
}
}
}
you have to do the following :
1- instead of doing for loop to fill the combobox set the combobox datasource equal to the data table and set the value member and display member
cbTypeofAccount.DataSource = dt;
cbTypeofAccount.DisplayMember = "type_Of_Acct";
cbTypeofAccount.ValueMember = "your table id";
2- change the dropdown style for the combobox to make it editable
cbTypeofAccount.DropDownStyle = ComboBoxStyle.DropDown;

Categories