Update DataGrid after insert with procedure - c#

I know this question was asked but I can't figure out why this action is so complex.
So I have a Produs table
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
This is my table's columns. I added via Data Sources GUI from Visual Studio a DataSet with the content of this table (no actual code wrote by me).
Now I have a procedure that will insert me a new row in this Table.
Here is the code:
private void dToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("connection-string-here");
string Query = "spGE_getProduse_Edit"; // Stored procedure name.
int Integer;
conn.Open();
// Creating SqlCommand object
SqlCommand com = new SqlCommand(Query, conn );
// Here we declaring command type as stored procedure:
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#IDProdus", 0);
com.Parameters.AddWithValue("#Denumire ",
denumireTextBox.Text.ToString());
com.Parameters.AddWithValue("#UM ",
uMTextBox.Text.ToString());
com.Parameters.AddWithValue("#Pret ",
Double.Parse(pretTextBox.Text));
com.Parameters.AddWithValue("#IDFurnizor ",
Int16.Parse(iDFurnizorTextBox.Text));
com.Parameters.AddWithValue("#IDCategorie ",
Int16.Parse(iDCategorieCombobox.SelectedValue.ToString()));
com.Parameters.AddWithValue("#IDTipProdus ",
Int16.Parse(iDTipProdusCombobox.SelectedValue.ToString()));
com.Parameters.Add("#IDProdusScris", SqlDbType.BigInt);
com.Parameters["#IDProdusScris"].Direction =
ParameterDirection.Output;
com.ExecuteNonQuery();
conn.Close();
Integer =
Int32.Parse(com.Parameters["#IDProdusScris"].Value.ToString());
}
Now after insert I want to update myGrid with the new record. I tried
dataGridView1.Refresh(); and dataGridView1.Update();, with no result.
Is there a way to update the grid? It looks like a simple task for VS, but I couldn't find a simple solution.
What I saw only and read on MSDN looked like some very complex operations just for a simple refresh. (It was about getting the state of the row and insert the row if the state was Added).
So is there any simple way to do this, or I have to write a method that will refresh my dataGridView every time I want (I mean to re-query my table and rebuild the dataSource)

Try like this:
dataGridView1.Refresh(); and dataGridView1.Update(); will not fetch updated records from db.
Source
You can use stored procedures are pre-complied
Create Procedure Sp_getProducts
as
BEGIN
SELECT TOP 1000 [IDProdus]
,[Denumire]
,[UM]
,[Pret]
,[IDFurnizor]
,[IDCategorie]
,[IDTipProdus]
,[OperatorAdaugare]
,[DataAdaugare]
,[OperatorModificare]
,[DataModificare]
FROM [Proiect].[dbo].[Produse]
END
Use this code which Uses Using Statements
using (SqlConnection conn = new SqlConnection("connection-string-here"))
{
conn.Open();
using(SqlCommand cmd=new SqlCommand("Sp_getProducts",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
da.Fill(ds);
gridView.DataSource = ds;
gridView.DataBind();
conn.Close();
}
}

Try resetting your datasource:
dataGridView1.DataSourcce = null;
dataGridView1.DataSource = [YOUR DATASET];
dataGridView1.Refresh();
dataGridView1.Update();

Related

Combobox added to datagridview losses its selection

I am trying to populate a datagrid table and add an additional combobox in a Winforms application to allow the user to select from an exception list.
The datagrid is populated using a Stored Procedure on SQL server.
(NOTE: due to my ITs security I have to go through a single server using linked servers to where the data is to query the data so the stored procedure uses dynamic SQL)
The data pulls properly and the additional combobox appears however once I select an exception on 1 row and try to go to the next row, the first combobox's selection disappears.
An additional question, given the nature or how I query the data, how would I update the data on the original sql tables from datagrid? Another stored procedure?
FYI, I'm a SQL developer but I'm fairly new to C#
My code is below for the datagridview method. Thanks in advance.
public void displayDataGridView(string param)
{
SqlConnection con = new SqlConnection("Data Source = SQLServer1; initial catalog=GlbDBNames; integrated security=true ");
{
SqlCommand cmd;
cmd = new SqlCommand(param, con);
cmd.CommandTimeout = 60 * 20;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dg_batchsummary.DataSource = ds.Tables[0];
dg_batchsummary.Columns[0].Width = 200;
dg_batchsummary.AutoGenerateColumns = false;
dg_batchsummary.AllowUserToAddRows = false;
DataGridViewComboBoxColumn ExceptionList = new DataGridViewComboBoxColumn();
ExcptionList.HeaderText = "Exception List";
ExceptionList.Name = "Newexcept";
ExceptionList.Items.AddRange("Item1","Item2","Item3");
dg_batchsummary.Columns.Add(ExceptionList);
}

Insert and select within same sp?

Here I came up with situation where I want insert records in temp temple and again want to dispaly that record to user.
I have created one sp in that sp created temp table, added record to that table and select record from temp table.How to show record to user in interface?
ExecuteNOnquery is used for inserting record and ExecuteReader is is used for selecting record.
Withing same sp,I have insert and select.So how to do that in code behind?
You should use ExecuteReader.
All it does - sends string of CommandText to server, executes it, and then builds SqlDataReader to read from.
So if your CommandText is a call to stored procedure - this procedure will be executed (so it will insert your data and select it back) and returned data will be available in SqlDataReader.
See MSDN for reference to ExecuteReader
You could do something like this
using(var con = new SqlConnection(conStr))
{
var cmd = new SqlCommand("MY_SP",con);
cmd.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds);
if(ds.Tables.Count > 0)
{
foreach(var dr in ds.Tables[0].Rows)
{
// Do stuffs with dr
}
}
}

Writing to SQL Server Database

I am having trouble writing my datagrid changes to the database, i am trying to type in the changes on the grid and then when Button_Add_Car is pressed i execute this code and write changes to the database but nothing is being written to the database.
private void Button_Add_Car(object sender, RoutedEventArgs e)
{
SqlConnection cn = new SqlConnection();
DataSet dt = new DataSet();
SqlDataAdapter da;
SqlCommandBuilder cmdBuilder;
cn.ConnectionString = (String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
cn.Open();
da = new SqlDataAdapter("SELECT * FROM Cars", cn);
cmdBuilder = new SqlCommandBuilder(da);
da.Fill(dt);
da.Update(dt);
cn.Close();
}
Am i on the right track using this method?
Am i using the correct SQL Query? I am confused between the SELECT/INSERT as i have found examples where people are using both to achieve what i want to do. Surely i should be using the INSERT statement.
I made my own custom SQL Command to manually insert into the database so it is in fact working:
SQLCmd("INSERT INTO Cars (Date, Time) VALUES(2014-10-10, '12:00:00')");
EDIT 1:
Thanks to marc_s i managed to achieve some sort of inserting but i believe i need to modify the value section to be inside an IF Statement which will check if it is a null or not and change value back to cr.Date and cr.Time as i am making use of a list. I am unsure of how to utilize the if statement in this way because it is currently entering blank rows, although its a step in the right direction:
CarRecord cr = new CarRecord();
carRecords.Add(cr);
SqlConnection con = new SqlConnection(String.Format(#"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
con.Open();
SqlCommand comm = new SqlCommand("INSERT INTO Cars VALUES (#Date, #Time)", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.SelectCommand.Parameters.Add(new SqlParameter("#Date", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.Parameters.Add(new SqlParameter("#Time", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Update(dt);
con.Close();
lets take your first code example.
take a look at the last 3 lines, first thing you do is to copy data from the table Cars and store that into the DataSet named dt.
then immediately after you store this dataset back into the database, without actually doing any changes.
if dot net is smart enough it wont do anything, since you didn't change anything between the fill and the update call.
what you probably should be doing is get the dataset from the datagrid or similar and store that one instead.
or do as you have started on in your second example of when you identity that a row is updated take the data from that row and construct an insert (or update) query to the database.

object reference not set to an instance of an object when using parameter

Can someone tell me how i can set the object reference to an instance? ....
Here, user_id is the parameter which takes a textbox value into the sql statement.
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
adap = new OracleDataAdapter("insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id,'172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt",con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20, "user_id").Value = textBox1.Text;
adap.Fill(ds,"A");
DataTable table = ds.Tables["A"];
dataGridView1.DataSource = ds.Tables["A"];
con.Dispose();
}
thanks!
edit
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
string str = "insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id, '172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt";
con.Open();
adap.InsertCommand = new OracleCommand(str, con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20).Value = textBox1.Text;
adap.InsertCommand.ExecuteNonQuery();
con.Dispose();
}
thanks everyone for your help!! i got it!
EDIT: There are multiple things wrong with your code:
You're not specifying the user_id parameter in the command, although it's in the SQL
You're trying to use the InsertCommand of the adapter even though you haven't specified any insertion SQL
You're trying to fill a dataset, but you haven't specified a query - just an insert command.
I suspect you shouldn't be using a data adapter at all. If you just need to insert some data, use:
using (var connection = new OracleConnection(...)
{
connection.Open();
string sql = "insert into banks_ben_branch_99 [... as before ...]";
using (var command = new OracleCommand(sql, conn))
{
command.Parameters.Add("user_id", OracleType.VarChar, 20)
.Value = textBox1.Text;
command.ExecuteNonQuery();
}
}
I suspect adap.InsertCommand is null in the following line:
adap.InsertCommand.Parameters.Add
On the previous line you use the following constructor:
adap = new OracleDataAdapter("insert into ...", con);
but this constructor initializes the SelectCommand, not the InsertCommand. Therefore adap.InsertCommand will still have its default value, null.
Your code then goes on to attempt to fill a DataTable using this adapter:
adap.Fill(ds,"A");
but this won't work either: you need a SelectCommand to do this.
To fill a DataSet, your code should probably look something like:
adap = new OracleDataAdapter("SELECT ... FROM ... WHERE ...", con);
adap.SelectCommand.Parameters.Add(... any parameters you need ...);
adap.Fill(ds, "A");
it is passing the break point now, no changes has been made to the oracle database tables! why is this happening.
I think you're misunderstanding how DataAdapters work.
To get data from the database into your DataTable, you need to:
Create an adapter with a SelectCommand
Call adapter.Fill to execute the SelectCommand and fill the DataTable with the result
To insert data into the database from your DataTable, you need to:
Insert a row into your DataTable with the data you want to insert
Create an adapter with an InsertCommand
Call adapter.Update to insert the data into the database.
Updating / Deleting rows in the database is similar to inserting, but uses UpdateCommand and DeleteCommand.
I think user_id is not a nullable column and it occurs when your parameter is empty. First thing is, parameter name does not match. After that, it still can happen when textbox is empty. It is better to check on client side for validation.
The parameter that you have given is null.

How can we use two queries in same click event?

I used the code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("server=kiran-b946c0f6d;
uid=sa;
pwd=123;
database=employe");
SqlCommand com=new SqlCommand("INSERT INTO Emplo VALUES('"+TextBox2.Text+"'",con);
com.Parameters.Add("Email_ID", SqlDbType.VarChar);
com.Parameters["Email_ID"].Value = TextBox2.Text;
con.Open();
Label3.Text = "successfully added";
SqlDataReader reader = null;
com = new SqlCommand("SELECT Email_ID FROM Emplo WHERE Email_ID='"
+ TextBox2.Text + "'",
con);
reader = com.ExecuteReader();
if (reader != null && reader.HasRows)
{
Label3.Text = "Emailid alraedy exist";
}
reader.Dispose();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
I intended to use Insert values in the database and if there is any duplicity,it will show the error.The duplicity is working properly.But insertion is not properly working.It will show inserted successfully.But the values are not doing insertion.
You're not actually calling com.ExecuteNonQuery() before overwriting the com variable.
You aren't running the insert at all - you set up the command and then overwrite it with your new select command.
Even if you were running the insert at that point your select that is coming after it would always be expected to return true because you've just inserted it. Additionally depending on the database structure if that database field is set to be unique (which seems to be what you are trying to enforce in the code) then I would expect a sql exception to be thrown as you try to insert something which already exists.
What you want to do is run the select to check if it already exists first. Then if it exists you can just stop. If it doesn't exist you can do the insert then.
Or better still write a single SQL statement (better yet a procedure) that does the check at the same time as the insert to try to prevent any possible issues relating to two threads doign the check and finding it doesn't exist and then two threads doing the insert causing one of them to fail most likely.

Categories

Resources