Alternative Ways In Adding New Rows in Datasource Data Grid View - c#

I'm creating a project in C# windows form. What I'm trying to do is add new rows in the datasource data grid view. But the problem is, the error says that adding new rows can't add programmatically in the datasource data grid.
Here's my method in fetching the data and transfer it in the data grid view.
public DataTable GetData(ClassName classVar){
SqlCommand cmd = new SqlCommand();
cmd.Connection = ...; // My connection string
cmd.CommandType = CommandType.Text;
cmd.CommandText = ...; // My Query
DataTable table = new DataTable();
table = ...ExeReader(cmd);
return table;
}
The Codes inside my form
DataTable getDataTable;
getDataTable = ClassQuery.GetData(classVar);
dgv_details.DataSource = getDataTable;
And this is my add button
dgv_details.Rows.Add(txtBox1.Text,txtBox2.Text);
What are the alternative ways in adding data inside the datasourced datagridview?
Thanks in advance.

Try the below code. First add row to datatable and then bind that table to datagridview.
DataRow dr = datatable1.NewRow();
dr[0] = "HAI"; // add data in first column of row
datatable1.Rows.InsertAt(dr, 0); // insert new row at position zero
datatable1.Rows.Add(dr); // addnew row at last

Related

C# mysql view only specific columns in data grid view

Short and probably easy question, I don't want to view in dataGridView columnID and few more columns as there is no use of viewing that info.
I have a clear code, the connection is open, the data loads fine and the comment code (btw most common solution in google) gives empty table with all columns (no rows).
I tried so many things that I can't even list them there :(
Any ideas?
DataTable SqlDataTable = new DataTable();
MySqlDataReader reader;
MySqlCommand sqlCommand = new MySqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM table_name";
reader = sqlCommand.ExecuteReader();
//while (reader.Read())
//{
// string columnID = reader["columnID"].ToString();
//}
SqlDataTable.Load(reader);
reader.Close();
sqlConnection.Close();
DataGridView = SqlDataTable;
First when U want view data in DataGridView U should set the data source of it's like
DataGridView.DataSource = yourDataTable
Second, if U want to hide DataGridView column, U most know the index of the column or the name and then you can use this code
I assume the first column is ID
So
By Index
DataGridView.Columns[0].Visible = false;
By Name
DataGridView.Columns["ID"].Visible = false;

C#: Fill DataGridView with DataTable creates empty table

I searched the web and Stack Overflow and found lots of descriptions on how to fill a DataGridView with the content of a DataTable. But still it does not work for me. My DataGridView shows the correct number of columns and rows, but they appear empty.
I use following method:
public void ShowDataInGrid(ref DataTable table)
{
BindingSource sBind = new BindingSource();
dbView.Columns.Clear();
dbView.AutoGenerateColumns = false;
sBind.DataSource = table;
dbView.DataSource = sBind; //Add table to DataGridView
dbView.Columns.Add("Date", "Date");
}
Before this I created a DataGridView of name "dbView" via the designer. I am not even sure, whether I need sBind. Without it I can bind the table directly to dbView, with the same bad result.
I suspect my table is the problem. It origins from a database (SQLite) and has several columns and rows (one of the columns has the name "Date"). It is definately filled with readable data.
I mainly read the table in using following commands (after this I manipulate the data in several different steps, like changing strings and adding numbers...):
string sql = "select * from Bank";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
table.Load(reader);
reader.Close();
table.AcceptChanges();
I think the problem might be, that the table entries are stored as objects and not as string, and hence can't be shown. That's why I tried to force the content to be strings with the following change to my table:
DataTable dbTableClone = new DataTable();
dbTableClone.Load(reader);
SQLiteDataReader reader.Close();
dbTableClone.AcceptChanges();
string[] dBHeader = new string[dbTableClone.Columns.Count];
dBHeader = ReadHeaderFromDataTable(dbTableClone); //own funktion, which reads the header
DataTable table;
table.Clear();
//will first create dbTable as empty clone, so I can set DataTyp of each Column
table = dbTableClone.Clone();
for (int col = 0; col > dBHeader.Length; col++) //first set all columns as string
{
dbTable.Columns[col].DataType = typeof(string);
}
foreach (DataRow Row in dbTableClone.Rows)
{
dbTable.ImportRow(Row);
}
This did not help me neither.
Another idea: I found some comments on similar problems, where it got apparently solved with quote: "I designed columns in the VS datagridview designer. Not the column name, but the column DataPropertyName must match with fields in database." Unfortunately I don't seem to be able to do/understand this.
Following you see one row of my input table.
Try fetching and setting to GridView this way
SqlLiteConnection con = new SqlLiteConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=DB.mdf;Integrated Security=True");
con.Open();
SqlLiteDataAdapter adap = new SqlLiteDataAdapter("select * from Bank", con);
DataSet ds = new System.Data.DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
Comment everything you've done so far, try this and let me know if this works for you or not. Change connection according to your DB.
I solved the problem.
The DataTable was fine. The problem was the setup of my DataGridView dbView. I set up dbView in the designer and somehow gave it a datasource. Now I set the datasource to "none" (In "DataGridView Tasks") and my data appears as intended.
Thanks to M Adeel Khalid for looking at my stuff. Him assuring to me that my code for the link was right, made me find the solution eventually.
At the end I really only needed to use a single line:
dbView.DataSource = table;

adding datarow to datagridview only adding to first column

I'm trying to pull a set of data from a database and shove it in to a datagridview. Problem is, when I do this, I get "system.data.datarow", and it only adds it to the first column (I've got 5). Here's my code.
SqlCommand sqlCom = new SqlCommand("some SQL query string", "SQL database connection info");
SqlDataAdapter adapter = new SqlDataAdapter(sqlComm);
DataTable table = new Datatable();
if (methodType = "SELECT")
{
sqlConn.Open();
adapter.fill(table);
foreach (DataRow row in table.Rows)
{
dgvCrsLookupResults.Rows.Add(row[0]);
dgvCrsLookupResults.Rows.Add(row[1]);
dgvCrsLookupResults.Rows.Add(row[2]);
dgvCrsLookupResults.Rows.Add(row[3]);
dgvCrsLookupResults.Rows.Add(row[4]);
}
}
Obviously, this only fills in the first column, but I can't figure out for the life of me how to add it to each column instead. When I use
dgvCrsLookupResults.Columns.Add(row[0]);
It just says that it has invalid arguments. I know I'm damn close, but I'm new to all of this, so I'm completely lost as to how to make that last jump. Thoughts?
Instead of looping foreach(DataRow row in table.Rows) use:
dgvCrsLookupResults.DataSource = table;
Remember set:
dgvCrsLookupResults.AutoGenerateColumns = True;
Or in designer create a columns for your DataGridView.
In column set DataPropertyName = ColumnName in DataTable
In this case -> dgvCrsLookupResults.AutoGenerateColumns = False;

update datatable inside a dataset

I want to know how to update a Datatable which is inside a dataset.I have a datatable in which i have details of some item.Now i want to add this into a dataset for some purpose and update it.Give me some suggesions to solve this..
this is my code:
DataRow dr;
dr = Basket_DataTable.NewRow();
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
Basket_DataTable.AcceptChanges();
Basket_DataTable is my datatable which i need to add to a dataset and update..
I believe you want to add new Rows to your existing DataTable in your DataSet. Instead of creating a new DataTable, your Basket_DataTable should refer to your data table in the data set.
Something like.
//Create new Row from your DataTable in DataSet
DataRow dr = yourDataSet.Tables["Basket_DataTable"].NewRow();
// here you can refer to your datatable with the index as well
//e.g. yourDataSet.Tables[0]
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
//Remember to add your row to the table.
yourDataSet.Tables["Basket_DataTable"].Rows.Add(dr);
In your current code you are not adding the new row to the datatable. Remember to include the row in the datatable.
If the DataTable is already in an existing DataSet, but you want to add it to another one, you need to create a copy first - A DataTable instance can only have one parent DataSet.
DataTable Basket_DataTable_copy = Basket_DataTable.Copy();
yourDataSet.Tables.Add(Basket_DataTable_copy);
Then you can do your updates on Basket_DataTable_copy
see DataTable.Copy on MSDN

Single datagridview row updating

Could you help with such problem:
I have two forms, datagridview and SQL database.
On Load event of my first form I'm select some data from my SQL database by using stored procedure(select query).
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("PROC001", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;
After that, I can filter or sort my datagridview by using dt.DefaultView.Filter = .... and display in my grid only filtered rows.
On CellMouseDoubleClick event my second Form2 appearing. In this form I update some value in database by clicking on Button1 and also after that I want to update my selected datagridview row. My quetions are:
1) How can I update only selected row in datagridview and do not execute stored procedure for all datagridview filling again.
2) My datagridview is already filtered, so if I execute procedure again, my filter has been disapeared. How can I avoid of this?
3) On Form2 I'm updating some database value, that is not included in my "select query" as selected field, but this value is affected on this query. Example:
SELECT Name, SecondName FROM tUsers
WHERE id = (SELECT DISTINCT id FROM tProcedures WHERE Code = 'First')
In my datagridview I can see Name and SecondName, but in Form2 I'm updating Code in tProcedures database table. So after updating I want to see my new data in datagridview, only in selected row and with current filter. I don't want to SELECT all data again to datagridview and broke my filter.
Is it possible to update single row? Could you provide some examples?
Because the DataGridView is using DataBinding, you have to update the underlying data source, in this case the DataTable. See How to: Edit Rows in a DataTable for how to do that.
For the filter issue, you would want to save and restore the filter:
var filter = dt.DefaultView.RowFilter;
UpdateData();
dt.DefaultView.RowFilter = filter;

Categories