My gridcontrol doesn't show datatable connected SQL Server - c#

In this form, I have just one gridcontrol and this datasource is datatable connected to SQL Server.
Bottom of the gridcontrol there are four buttons named select, insert, delete, modify gridcontrol.
This is my code, and it has click event when insert button is clicked.
private void InputButton_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(mssql))
{
conn.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("Insert into [Department] (부서코드, 부서명) values (#부서코드, #부서명)", conn);
cmd.Parameters.AddWithValue("#부서코드", "2101");
cmd.Parameters.AddWithValue("#부서명", "영업부");
sqlDataAdapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result < 0)
{
MessageBox.Show("There are errors when inserting data");
}
else
{
sqlDataAdapter.Update(dataTable);
gridControl1.RefreshDataSource();
conn.Close();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I click insert button, there are not any event in gridcontrol so I don't see any change of insert query. However, close form and reopen form, then I can see my insert query in gridcontrol.
Even I use gridcontrol.refreshdatasource but I don't know what I can't see any changes soon after I click
insert button. Is there any answers?
Even I tried use try catch, but I don't know my issue. I want to show gridcontrol.refreshdatasource when I click insert query.

To insert SQL Server data using a GridControl and DataTable in C# Winform, you can follow these steps:
Create a connection string to connect to the SQL Server database. You can use the SqlConnection class to create the connection string.
string connectionString ="Server<server_name>;Database<database_name>;User Id=<username>;Password=<password>;";
Create a DataTable object to store the data that will be displayed in the GridControl. You can add columns to the DataTable object to match the columns in the SQL Server table.
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
Create a SqlDataAdapter object and use it to fill the DataTable object with data from the SQL Server table. You can use the SELECT statement to retrieve the data.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM <table_name>", connectionString);
adapter.Fill(dt);
Set the DataSource property of the GridControl to the DataTable object to display the data in the GridControl.
gridControl1.DataSource = dt;
Add a new row to the DataTable object using the NewRow method, and set the values of the columns.
DataRow row = dt.NewRow();
row["ID"] = 1;
row["Name"] = "Bob Ross";
row["Age"] = 52;
dt.Rows.Add(row);
Create a SqlCommand object to insert the data into the SQL Server table. You can use the INSERT INTO statement to insert the data.
SqlCommand cmd = new SqlCommand("INSERT INTO <table_name> (ID, Name, Age) VALUES (#ID, #Name, #Age)", connection);
cmd.Parameters.AddWithValue("#ID", row["ID"]);
cmd.Parameters.AddWithValue("#Name", row["Name"]);
cmd.Parameters.AddWithValue("#Age", row["Age"]);
cmd.ExecuteNonQuery();
Refresh the DataTable object and the GridControl to reflect the changes.
dt.Clear();
adapter.Fill(dt);
gridControl1.RefreshDataSource();
Note that you should handle any exceptions that may occur while inserting data into the SQL Server table, and also make sure to dispose of any database connections, commands, and adapters after use.
Hope this helps.

Related

Delete all access database table data

I have an access database that I am manipulating with C#.
I have connected to it, retrieved a data-set from it and can add rows to a table. Now I am trying to clear a table and I am unable to get it to work.
I have tried TRUNCATE TABLE table_name but that throws an exception saying that I must use either DELETE, INSERT, PROCEDURE, SELECT or UPDATE and I have tried Delete FROM table_name However that throws an DBConcurrenceyException.
Here is what I have to tried to clear the table:
private void ClearBut_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableClear = new OleDbDataAdapter();
OleDbCommand command;
command = new OleDbCommand("DELETE FROM TestTable", con);
dtaAdpTestTableClear.DeleteCommand = command;
foreach (DataRow row in dsWCSDHDB.Tables["TestTable"].Rows)
{
row.Delete();
}
dtaAdpTestTableClear.Update(dsWCSDHDB.Tables["TestTable"]);
}
My other add method
private void Add_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableInsertNewRow = new OleDbDataAdapter();
OleDbCommand command;
// Create the InsertCommand.
// This is needed as DataAdaptor.InsertCommand() is called during the update to insert the row into the database. It requires an insert query
command = new OleDbCommand("INSERT INTO TestTable (id, someData) " +"VALUES (?, ?)", con); //We create a dbcommand the command is, Querytype, what we are doing with it, what table, (columns we are using), concat, Values we will be adding(as ? for now as we will pass this data in latter), connection to the database
command.Parameters.Add("id", OleDbType.Char, 5, "id"); //this is where we add a parameter to the command function. we add one per column in the row (columns we are using name, value type, column length, source column, these parameters will replace the ? in the query above
command.Parameters.Add("someData", OleDbType.VarChar, 40, "someData");
dtaAdpTestTableInsertNewRow.InsertCommand = command;// we attach this command to the Insert command function of the adapter that we are using
//Create the new row
DataRow row = dsWCSDHDB.Tables["TestTable"].NewRow(); //Create a new empty row that is formated for the TestTable table
row["someData"] = AddValueTextBox.Text.ToString();// add in the values
//Add the new row to the dataset table
dsWCSDHDB.Tables["TestTable"].Rows.Add(row); //adds this new row to the clients dataset
//Updates the database table with the values of the clients dataset Table
//For this to work you need to build a proper data adapter that is using a query taylered for the table you are using.
//Unfortunately although it would be nice to be able to add and use tables to the database with out changing the code you cant build a generic one that works for all tables in the database.
//this is because different tables can have different fields and column lengths .
//there is a example of how to build one below
//Update the database table with the values of the clients dataset Table
dtaAdpTestTableInsertNewRow.Update(dsWCSDHDB.Tables["TestTable"]); // using the adapter that we created above we update the database with the clients dataset.
}
You will just need to call ExecuteNonQuery
private void ClearBut_Click(object sender, EventArgs e)
{
string comand = "DELETE FROM TestTable";
OleDbCommand cmd = new OleDbCommand(comand, con);
cmd.ExecuteNonQuery();
}

Sending DataTable to a stored procedure from C#

Need some help with DatagridView & DataTable.
Basically I have a DatagridView which OnLoad populates with the data from a table in SQL Server
When I click a button on UI, this DataGridView adds a new column to the front of grid "Update" which is a checkbox column
Now when the user ticks all those rows which needs updating and clicks Update...
I want to update all the rows which are ticked (for example: I wish to set the owner of these rows from Person A to Person B)
I've looked at DataTable but I'm confused
My logic is to add all the selected columns to a DataTable and send this to a stored procedure in SQL Server which would update the values.
If I'm not mistaken, I shall be sending a DataTable with just an ID column followed by From & To (owners) to the stored procedure.
Please guide me if I'm wrong, any help would be immensely appreciated.
private DataTable getDataGridID()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
foreach (DataGridViewRow row in dgTeamDashboard.Rows)
{
if (Convert.ToBoolean(row.Cells["Update"].Value) == true)
dt.Rows.Add(row.Cells["ID"].Value);
}
return dt;
}
I've now progressed upto this point where I have a DataTable with all those ID's whose update column is ticked.
I'm hopeful, I'm heading in the right direction. Comment if I'm not
Further Update:
I've now create a stored procedure which accepts UserDefinedTableType and a destinationOwnerID as parameter and updates the actual table with the supplied OwnerID for all those leads whose ID matches the records from DataTable.
Create Procedure [activity].[udpUpdateActivityLead]
#ActivityLeadTable ActivityLeadType READONLY,
#OwnerTo int
AS
BEGIN
UPDATE [activity].[tblActivity]
set [activity].[tblActivity].[IDOwner]= #OwnerTo
from #ActivityLeadTable
where [activity].[tblActivity].[ID]=[#ActivityLeadTable].[ID];
END
Finally I got this function in my UI which works like a GEM. Happy ending...I can go to sleep now...
public void updateActivityLead()
{
SqlConnection con = new SqlConnection(OpSupLib.MyConnectionString);
SqlCommand cmd = new SqlCommand();
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "[activity].[udpUpdateActivityLead]";
SqlParameter p1 = new SqlParameter();
p1.ParameterName = "#ActivityLeadTable";
p1.Value = getDataGridID();
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter();
p2.ParameterName = "#OwnerTo";
p2.Value = ((ComboBoxItem)cmbUpdateTo.SelectedItem).HiddenValue;
cmd.Parameters.Add(p2);
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}

DataGridView Datatable Copy-Keep-Add-Update rows

I am developing Windows application (environment: Visual Studio 2010 and C#)
I use a datagridview with records completed by datatable dt:
dataGridView1.DataSource = dt;
This datatable has 20 columns with 1 identity column - column[0] = autonumber, and column[1] called “RecordChecked” implemented as Boolean (checkbox).
I need to solve next problems:
Select rows filtered by column[2] (in code example: DrawingNo='DM-3012');
Keep these records
Add exactly the same records below existing but update column[2] with different value like DrawingNo='DM-3013' (so we’ll have twice more records)
I started from copying records from one datatable into another (see code below) – this code works ok, but then stacked how to add copied records below existing and then update them:
DataTable dtSource = ((DataTable)dataGridView1.DataSource);
DataTable dtTarget = new DataTable();
dtTarget = ((DataTable)dataGridView1.DataSource).Clone();
DataRow[] rowsToCopy;
rowsToCopy = ((DataTable)dataGridView1.DataSource).Select("DrawingNo='DM-3012'");
foreach (DataRow temp in rowsToCopy)
{
dtTarget.ImportRow(temp);
}
dt = dtTarget;
Thanks,
I think I found a good approach to this problem.
1. Create Stored Procedure (mySP).
This SP creates temp table where we located all records selected with clause 'WHERE DrawingNo = #CopyFrom'.
Then this SP updates temp table with statement like:
UPDATE #TempTbl1 SET RecChecked = 0, DrawingNo = #CopyTo WHERE DrawingNo = #CopyFrom.
Then SP inserts updated records from temp table into the main table.
Finally SP drops temp table and selects all needed records from the main table.
2. Now we can run this SP in app and bind data to datagridview like:
//Run SP
using (SqlCommand cmd = new SqlCommand("mySP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CopyFrom", SqlDbType.VarChar).Value = sValueFrom;
cmd.Parameters.Add("#CopyTo", SqlDbType.VarChar).Value = sValueTo;
con.Open();
cmd.ExecuteNonQuery();
}
//Create SELECT statement
string strSelect = "SELECT Recid, RecChecked, DrawingNo, ... FROM Tbl1 WHERE DrawingNo = '" + sValueTo + "'"
//fill dataadapter
sda = new SqlDataAdapter(#strSelect, con);
dt = new DataTable();
sda.Fill(dt);
That works!

Updating a table on DB considering changes on a grid in C#

I'm filling a Data Grid in C# (WinForms) via a System.Data.DataTable. DataTable is filled from a DB table via ODP.
I have a data navigator in Data Grid for updating, deleting and inserting rows.
I want to use DataTable to commit all changes made in Data Grid to the database.
I have to use OracleDataAdapter but I couldn't figure out how to achieve this.
What kind of a CommandText should I use to achieve all three commands (update, delete, insert)?
The code below didn't work (maybe because CommandText I inserted is not appropriate)
public void ExecuteNonQuery(string commandText, OracleCommand oracleCommand, CommandType commandType, DataTable dataTable)
{
oracleCommand.CommandText = commandText;
oracleCommand.CommandType = commandType;
try
{
oracleCommand.Connection = m_Connection;
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(oracleCommand);
oracleDataAdapter.Update(dataTable);
}
catch (Exception)
{
LoggerTrace.Instance.Write(TraceEventType.Error, LoggerTrace.LoggerTraceSource.DatabaseManagerError, "Query could not be executed!");
throw;
}
}
for insert create a new row in data table and insert into data table ,for update update the value and finally make save change of data set or data table
OracleCommandBuilder producess the appropriate insert, update and delete queries after the select query is inserted.
string selectCommand = "select * from Table";
oracleDataAdapter.SelectCommand = new OracleCommand(selectCommand, m_Connection);
OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(oracleDataAdapter);
DataTable dataTable = new DataTable();
oracleDataAdapter.Fill(dataTable);
After OracleCommandBuilder build the command this way you can execute any updates in the DataTable like this:
oracleDataAdapter.Update(dataTable);
Sequences, virtual columns etc. are not allowed.

C# write datagridview data into a SQL Server table

I have a four column table in a SQL Server database. The info for the first three columns is supplied by another source. Column 4 is set to null by default.
I then have a win form with a datatable that populates with the information from the SQL Server database using the following code:
public DataTable populateFormList()
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.sqlConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM of_formlist_raw", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
datagridview2.DataSource = populateFormList();
datagridview2.Refresh();
Now that works fine in obtaining my data.
The user can then make changes to the null values in column 4.
How can I easily write these changes from the datatable back into the SQL Server table?
In other words, once the on screen datatable has additional values, how can I then store the updated information back in the SQL Server database from which it was originally obtained from?
Thanks.
Try something like this and just pass (DataTable)datagridview2.DataSource as the data table:
private static void BulkInsertToSQL(DataTable dt, string tableName)
{
using (SqlConnection con = new SqlConnection(_DB))
{
SqlBulkCopy sbc = new SqlBulkCopy(con);
sbc.DestinationTableName = tableName;
//if your DB col names don’t match your data table column names 100%
//then relate the source data table column names with the destination DB cols
sbc.ColumnMappings.Add("DBAttributeName1", "DTColumnName1");
sbc.ColumnMappings.Add("DBAttributeName2", "DTColumnName2");
sbc.ColumnMappings.Add("DBAttributeName3", "DTColumnName3");
sbc.ColumnMappings.Add("DBAttributeName4", "DTColumnName4");
con.Open();
sbc.WriteToServer(dt);
con.Close();
}
}
2 options, with or without TableAdapter.
I would recommend to read this in MSDN for TableAdapter
They're using BindingSources too, which are excellent components, easy-to-use.
Without TableAdapter, read this, the "Update Records Using Command Objects" part.

Categories