Retrieving selected checkedlistbox - c#

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.

Related

c# asp.net Index was out of range. when I trying to select a row

I have a gridview on my page. And I have 2 snippets of SQL code to binds that gridview.
First one is run on page load. If there are records returned from the first SQL, I can select a row on gridview.
But the problem is when there is no record returned from the first SQL, I have button that runs another SQL and binds its result to the gridview too. But when I try to select a row, I get this error:
Index was out of range. when I trying to select a row Must be non-negative and less than the size of the collection. Parameter name: index
My code is like that
First SQL (its run on page load)
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and thats the second SQL that when runs when I click button
void listelehepsi()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
baglanti.Close();
}
and this is the GridView1_SelectedIndexChanged event
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int secili;
secili = GridView1.SelectedIndex;
GridViewRow row = GridView1.Rows[secili]; // I GOT ERROR HERE
TextBox1.Text = row.Cells[1].Text;
}
why Am I getting this error ?
EDIT--
I got solve changing the page load sql like this;
void listele()
{
baglanti.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * From kayitlar where durum='Çözülmedi' or durum='İşlem Yapılıyor'", baglanti);
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
GridView1.DataSource = dataTable;
if (!IsPostBack)
{
GridView1.DataBind();
}
else
{
//
}
baglanti.Close();
}
Make sure that you are not rebinding your datagrid on postback - you can do this in your PageLoad event - something like
if (!IsPostback)
{
... bind your datagrid
}
In the GridView1_SelectedIndexChanged event, could you simply do a RowCount to see if the value is != 0 before the other code runs?
if (GridView1.RowCount <= 0)
{
return;
}

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.

data is not getting deleted from database

In windows desktop application form I am using this code for deleting data from datagridview and database ,I have taken one checkbox column in dataridview ,If I click on checkbox row is getting deleted at that moment from datagridview ,but not from the database therefore when i reload form i can see that row again ,where I am going wrong?
public partial class EditEngClgList : Form
{
private OleDbConnection acccon = null;
private OleDbDataAdapter da = null;
private DataTable dt = null;
private BindingSource bs = null;
private OleDbCommandBuilder cmdb = null;
public EditEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
MessageBox.Show("Error:" + err);
}
string sql = "Select * From EngColeges order by EngClgID";
da = new OleDbDataAdapter(sql, acccon);
cmdb = new OleDbCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dataGridView1.Columns[1].Visible = false;
dataGridView1.Columns[2].HeaderText = "Engineering College Name";
dataGridView1.Columns[3].HeaderText = "Adress";
dataGridView1.Columns[4].HeaderText = "Entrance Type";
dataGridView1.Columns[2].Width = 400;
}
private void button4_Click(object sender, EventArgs e)
{
List<int> checkedclg = new List<int>();
DataRow dr;
List<int> checkedclgid = new List<int>();
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
}
foreach (int k in checkedclg)
{
dr = dt.Rows[k];
dt.Rows[k].Delete();
foreach (int j in checkedclgid)
{
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
oleDbCommand.Parameters.Add("#clgID", OleDbType.Integer).Value = j;
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
}
}
}
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Delete"].Value) == true)
{
checkedclg.Add(i);
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
}
Looks like the wrong cell value is being passed to Convert.ToInt16? It's using the "Deleted" column instead of your ID column.
Also you can delete all the rows in one sql statement using the where in clause, for example:
DELETE FROM table WHERE id IN (1, 2, 3, 4)
Insted of storing value of Delete like this
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
storing The values of primary key column like this deletes data properly from database Also
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["EngClgID"].Value));
You must change this line:
checkedclgid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["Delete"].Value));
to the following:
checkedclgid.Add(Convert.ToInt32(dataGridView1.Rows[i].Cells["CellInTheInvisible‌​Column"].Value));
Because you're converted a boolean type to Int16 and then you're used it in your query for checking with ID in your related table.
OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM EngColeges WHERE EngClgID = #clgID", acccon);
So, you must store ID of rows that you want to delete them.
I think first of all you are deleting the row and then you are attempting to delete it from database. First of all you delete the row from database and then again call the select query for that table.
All you have right now is a command. You need your OleDbDataAdapter, and pass the command to it:
...
da = new OleDbDataAdapter(sql, acccon);
da.DeleteCommand = oleDbCommand;
More Info: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx
Just replace these two lines:
oleDbCommand.Prepare();
oleDbCommand.ExecuteNonQuery();
With:
da.DeleteCommand = oleDbCommand;
References:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.deletecommand.aspx

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}

Adding row by row in GridView in runtime

I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();

Categories