Not able to bind the grid view in code behind desktop application - c#

I have a grid view which lists all the customers.
I am binding it in the load time of Form which is placed in the child of MDI.
Columns in the grid view is predefined at the design time.
My code for the Form_Load() event is:
try
{
cn = db.createConnection();
if (cn.State == System.Data.ConnectionState.Open)
{
cn.Close();
}
cn.Open();
cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy') as BillDt from BillMaster", cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
cn.Close();
da.Dispose();
ds.Dispose();
cmd.Dispose();
}
}
I checked the program execution by putting the breakpoints. The data is fetched exactly as database in the DataSet and Immediate Window the value of particular cell of grid shows the exact value but the problem is when the form is loaded the grid remains empty. And creates the number of blank rows same as the number of rows fetched from the database.
What should I do to tackle this error.
Please help.

Change
dataGridView1.AutoGenerateColumns = false;
to true. Remove
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}

first thing and maybe I am missing something but:
this is redundant, I would remove it, it could be part of the problem
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}
this should already take care of that
dataGridView1.DataSource = ds.Tables[0];

try
{
cn = db.createConnection();
if (cn.State == System.Data.ConnectionState.Open)
{
cn.Close();
}
cn.Open();
cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy') as BillDt from BillMaster", cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds.Tables[0];
//Or you can use
//dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
cn.Close();
da.Dispose();
ds.Dispose();
cmd.Dispose();
}
}
Hope it helps you

Related

Why do I get the value System.Data.DataRowView? c#

Why do I get the value System.Data.DataRowView? c# + sqlserver
I'm trying to add data to my table but ne system.Data.rowview and I don't know how to do it so that it doesn't come out
Why do I get the value System.Data.DataRowView? c# + sqlserver
This is where I load the items inside the Checklixbox
public void Cargar_Requerimientos(string Id_CR)
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_CR, Requisitos, Id_RS FROM Requerimientos WHERE Id_CR =#Id_CR ", cn);
cmd.Parameters.AddWithValue("Id_CR", Id_CR);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
//DataRow dr = dt.NewRow();
//dr["Requisitos"] = "Seleciona un Requisitos";
// dt.Rows.InsertAt(dr, 0);
///////////////////////////////////////
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
checkedListBox1.DataSource = dt;
//bool state = true;
// for (int i = 0; i < checkedListBox1.Items.Count; i++)
// checkedListBox1.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
//dr = dt.NewRow();
enter code here
try
{
//checkedListBox1.DataSource = dt.Columns[0].ToString();
//dt.Columns[0].ToString();
//checkedListBox1.DataSource = dt.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here I upload the data from combobox1 to checklistbox1
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// checkedListBox1.Enabled = false;
{
if (comboBox1.SelectedItem.ToString() == null)
{
checkedListBox1.Enabled = true;
}
}
if (comboBox1.SelectedValue.ToString() != null)
{
string Id_CR = comboBox1.SelectedValue.ToString();
Cargar_Requerimientos(Id_CR);
}
Result:
The CheckListBox does not directly support a DataSource, which is why the property is hidden from intellisence.
Usually it is correct to set the DataSource after setting the DisplayMember and ValueMember properties, to avoid multiple refresh calls, but to avoid your issue, you have to set the DataSource property first:
checkedListBox1.DataSource = dt;
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";

loop through dataset from sqlitereader c#

I am getting data from a database via this:
public static DataSet read_db(string sql)
{
DataSet ds = new DataSet();
try
{
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source=movies.db;Version=3;");
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
//reader = command.ExecuteReader();
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
{
adapter.Fill(ds);
}
m_dbConnection.Close();
return ds;
}
catch (SQLiteException ex)
{
string code = ex.Message.ToString();
MessageBox.Show("Error connection to database: " + code);
return ds;
}
}
Now I am trying to loop through this dataset, and get the values from the database, was using a regular datareader from sQLite, but that wont work because it keeps the connection open until I am done reading, which means as long as my application is open.
So now I have to change all my datareaders to a way with the dataset, this was my previous datareader way:
SQLiteDataReader reader = database.read_db("select * from proxies");
while (reader.Read())
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(proxytable);
row.Cells[0].Value = reader["id"];
row.Cells[1].Value = reader["proxy"];
row.Cells[2].Value = reader["port"];
row.Cells[3].Value = reader["username"];
row.Cells[4].Value = reader["password"];
if (reader["dead"].ToString() == "0")
{
status = "ok";
}
else if(reader["dead"].ToString() == "2")
{
status = "not tested";
}
else
{
status = "ok";
}
row.Cells[5].Value = status;
this.proxytable.Rows.Add(row);
}
How can I change this to work with the dataset? If possible with as little change needed because I have been using this alot.
try Like this....
DataSet ds= database.read_db("select * from proxies");
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow drw in ds.Tables[0].Rows)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(proxytable);
row.Cells[0].Value = drw ["id"];
row.Cells[1].Value = drw ["proxy"];
row.Cells[2].Value = drw ["port"];
row.Cells[3].Value = drw ["username"];
row.Cells[4].Value = drw ["password"];
}
}

How to insert images in DataGridView from SQL database using C#

I m working on an application where 5 images saved on a single id in the database. Now I want to retrieve these images in a datagrigview whenever they are called. My following code is working good with picturebox but I want multiple images containing the same pincode in datagridview from SQl server database.
try
{
string sql = "Select IMAGE from UserInput where PINCODE = '" + txt_LPin.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
//txt_LName.Text = reader[0].ToString();
byte[] img = (byte[])(reader[1]);
if (img == null)
pb_get1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pb_get1.Image = Image.FromStream(ms);
}
}
else
{
txt_LPin.Text = "";
txt_LName.Text = "";
pb_get1.Image = null;
MessageBox.Show("This ID does not exist.");
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
I have tried following code for dataGridView but it shows cross mark intead of image on place of image.
SqlDataAdapter adpat = new SqlDataAdapter();
adpat.SelectCommand = new SqlCommand("select IMAGE from UserInput", conn);
DataTable table = new DataTable("UserInput");
adpat.Fill(table);
//create image column:
DataGridViewImageColumn photoColumn = new DataGridViewImageColumn();
photoColumn.DataPropertyName = "Picture";
photoColumn.Width = 200;
photoColumn.HeaderText = "Picture column";
photoColumn.ReadOnly = true;
photoColumn.ImageLayout = DataGridViewImageCellLayout.Normal;
dataGridView1.Columns.Add(photoColumn);
//bind data to dgv:
dataGridView1.DataSource = new BindingSource(table, null);
To insert images in gridview ,you can use:
1) We need datasource:
dataGridView1.DataSource = datasouce;
2) create an image column by writing;
DataGridViewImageColumn img = new DataGridViewImageColumn();
img.Name = "img";
img.HeaderText = "Image Column";
img.ValuesAreIcons = true;
dataGridView1.Columns.Add(img);
3) and Finally
int number_of_rows = dataGridView1.RowCount;
for (int i = 0; i < number_of_rows; i++)
{
if (dataGridView1.Rows[i].Cells[6].Value.ToString() == "true")
{
Icon image = Properties.Resources.succcess_icon;
dataGridView1.Rows[i].Cells["img"].Value = image;
}
else
{
Icon image =Properties.Resources.cancel_icon;
dataGridView1.Rows[i].Cells["img"].Value = image;
}
}
Problem is Solved by the following line of codes;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Image,Name from UserInput where PINCODE = '" + txt_LPin.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();

Why I am not getting data displayed in my grid?

I am using a grid to be bounded through code whose columns are defined at design time.
My code for binding the grid in the form_load() is :
private void SearchForm_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
try
{
cn = db.createConnection();
if (cn.State == System.Data.ConnectionState.Open)
cn.Close();
cn.Open();
cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy')as BillDt from BillMaster", cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}
ds.Dispose();
cmd.Dispose();
da.Dispose();
cn.Close();
}
I debugged the program and the data is assigned to the each field that is observed from the Immediate Window while debugging but when the form is displayed the data does not appear. And number of blank row as fetched from the dataset are created.
How do I solve this? Please help.
Try this:
dataGridView1.DataSource = ds; // dataset
dataGridView1.DataMember = "TableName";//TableName
Hope it will work.

Datagridview not updating/refreshing

I have a DataGridView made of a DataSet of a table from the DB. When I delete a row, it is updated in the database but it is not removed from the GridView. Only when I restart the application does it get removed from the GridView.
Please help
You need to reset the binding on your bindingsource.
bindingSource.ResetBindings(false);
This is a very simple process.
1.) Create a Binding Source
2.) Set the Datasource for this object to your Dataset Table.
3.) Set The datasource for your DatagridView as the Binding source Object.
Code Example:
Dataset ds = new Dataset();
BindingSource bs = new BindingSource()
bs.Datasource = ds.Table[0];
DatagridView.Datasource = bs;
Now, Any changes you make in the DataTable will ripple through to your GridView automatically.
Hope this helps you?
if you are showing your table in dgv and for deleting something from that table you have a button on your win form. you chose let's say ID and click "delete" button for delting an item from db table. Here is that code:
private void btn_Delete_Click(object sender, EventArgs e)
{
int selectedCellCount = dgv.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
string selection;
for (int i = 0; i < selectedCellCount; i++)
{
selection = dgv.SelectedCells[i].Value.ToString();
string qs_delete = "DELETE FROM yor_table WHERE id = '" + selection + "';";
try
{
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = qs_delete;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
//don't forget to load your table again in dgv
string qs_select = "SELECT * FROM your_table";
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Clear();
dgv.DataSource = dataTable;
try
{
conn = new MySqlConnection(cs);
cmd = new MySqlCommand(qs_select, conn);
conn.Open();
da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
cb = new MySqlCommandBuilder(da);
dgv.DataSource = dataTable;
dgv.DataMember = dataTable.TableName;
dgv.AutoResizeColumns();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
You'll notice here that i have MySQL db but don't bother yourself with that.
If database is updated and you want to refresh DataGridView, call this:
this.<table name>TableAdapter.Fill(this.<DB name>DataSet.<table name>);
For example: Where is name of your table (for example Customers) and is name of your database (for example MyDB).
this.CustomersTableAdapter.Fill(this.MyDBDataSet.Customers);
You have to call this function after every deletion(Re-bind Grid).
void BindGrid()
{
YourDataGridView.DataSource = dataset;
YourDataGridView.DataBind();
}

Categories