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.
Related
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";
I'm trying to update a table from the gridview of tool to the SQL database. The problem is it's not getting updated in the database.
Below is my code for the button click which updates the database:
while debugging the code i found that the data table DT is fetching only the source values not the updated one in the grid view....
Is there any property in the grid view which accepts these change and updates the DT table ?
public partial class BusinessRules : Form
{
//Declaration Part
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");
private string sqlconn; // query and sql connection
private SqlDataAdapter SDA = new SqlDataAdapter();
DataTable DT = new DataTable();
SqlCommandBuilder scb = new SqlCommandBuilder();
private void button_retreive_Click(object sender, EventArgs e)
{
string commandText = "CoSD.RetreiveBusinessRulesTool";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
cmd.Parameters.Add("#CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
try
{
con.Open();
SDA.SelectCommand = cmd;
DT = new DataTable();
SDA.Fill(DT);
int count1 = DT.Rows.Count;
if (DT.Rows.Count > 0)
{
dataGridView.DataSource = DT;
dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;
}
else
{
MessageBox.Show("No Business Rules Found");
}
}
catch (SqlException ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
}
private void button_update_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
scb = new SqlCommandBuilder(SDA);
SDA.Update(DT);
// confirm
MessageBox.Show("Updates successfully submitted to CoSD");
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
In the try, put this
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
In your initializer call
SqlDataAdapter sda= new SqlDataAdapter("SELECT * FROM someWhere", connectionString);
DataTable dt = new DataTable();
The problem is that you refresh the datagridview before submitting the changes, thus deleting anything inputted
**** EDIT ****
This is exactly what my code in a project I did a little while back looks like:
namespace TowerSearch
{
public partial class EditParts : Form
{
const string conString = ConString.conString;
static DataClasses1DataContext PartsLog = new DataClasses1DataContext(conString);
static Table<Part> listOfParts = PartsLog.GetTable<Part>();
SqlDataAdapter sda;
SqlCommandBuilder scb;
DataTable dt;
public EditParts()
{
InitializeComponent();
}
//Load and refresh the dataGridView
private void showData()
{
SqlConnection con = new SqlConnection(conString);
sda = new SqlDataAdapter("SELECT * FROM Parts", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void EditParts_Load(object sender, EventArgs e)
{
showData();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
dataGridView1.Refresh();
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("Saved");
showData();
}
catch (Exception ee)
{
MessageBox.Show("There is an error in the data!\nCheck if there are any blank spots besides Quantity.");
}
}
}
}
That definitely works, so try the code with the show data. I'd suggest just copying it verbatim first to see if it would work.
**** EDIT 2 ****
Another thing that you could try if you haven't managed to get it already is add a bindingSource. To do this, drag a bindingSource onto your dataGridView and then set the DataSource option to the table of the DB that you wan't to display
Hope that helps!
private void BrokerWiseSalesReport_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = null;
dataGridView1.Rows.Clear();
ds = GetBrokerDetailspageload();
//int ii = 0;
if (ds.Tables[0].Rows.Count != 0)
{
dataGridView1.DataSource = ds.Tables[0];
}
}
In Dataset[ if (ds.Tables[0].Rows.Count != 0)] I am getting the No of rows but
while storing in gridview using the statement
dataGridView1.DataSource = ds.Tables[0];
i am Getting no of rows as null
I am using c# connecting with Mysql
Only thing is m Not able to store the data in gridview from dataset
The which m using to store the data set data to gridview is right?
just guide me
dataGridView1.DataSource = ds.Tables[0];
You need to use MySqlDataAdapter.
private void BrokerWiseSalesReport_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = null;
dataGridView1.Rows.Clear();
ds = GetBrokerDetailspageload();
MySqlDataAdapter msd= new MySqlDataAdapter();
msd.Fill(ds);
//int ii = 0;
//if (ds.Tables[0].Rows.Count != 0)
// {
dataGridView1.DataSource = ds;
// }
}
Please let me know the further issues.
Update
public DataSet GetBrokerDetailspageload()
{
MySqlConnection mycon=new MySqlConnection("Your connection string");
string str = "SELECT sm.BrokerName,st.ID,sm.SalesCode,sm.BillNo,sm.SalesBy,st.ProductName,st.Quantity,st.SalesRate,st.NetWeight,st.Expense,st.Amount,st.VatP,St.VatAmt FROM salesmaster sm INNER JOIN salestransaction st ON sm.SalesCode=st.SalesCode";
MySqlCommand cmd=new MySqlCommand(str,mycon);
DataSet ds=new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
private void BrokerWiseSalesReport_Load()
{
DataSet ds = new DataSet();
ds = null;
ds=GetBrokerDetailspageload();
dataGridView1.DataSource = ds.Tables[0];
}
I think you are missing one line of code.
Add this line after dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
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
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();
}