Basic method to export cells values from GridView to SQL table - c#

I need to read i little course about how to export a gridView in DevExpress to a SQL table..
like the values First Name, Father Name, Last Name to a table Employee and i have many rows..
how can I loop into every row and send data to the database..
Thx in advance
I tried this code:
string sql = #"INSERT INTO Emp (#FName, #MName,#LName, #Code, #TaxNb, #SSN, #EmploymentType, #DOB, #MarStat, #RegNum, #BadgeNum, #HireDate, #TaxSince, #HireSince, #ArEmpName, #ArFatherName, #ArLastName, ArPayUnit)";
DataTable table = new DataTable();
try
{
SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = command;
connection.Open();
// for (int i =0; i< gridView3.RowCount; i++)
//{
//command.Parameters.Add(#FirstName, gridView3.GetRowCellValue(i,gridView3.Columns));
//adapter.InsertCommand.ExecuteNonQuery();
//}
SqlParameter[] MyParams = new SqlParameter[28];
MyParams[0] = new SqlParameter("#FName", SqlDbType.VarChar, 20);
MyParams[0].SourceColumn = FirstName;
command.Parameters.Add("#FName", SqlDbType.VarChar, 20);
MyParams[1] = new SqlParameter("#MName", SqlDbType.VarChar, 20);
MyParams[1].SourceColumn = FatherName;
MyParams[2] = new SqlParameter("#LName", SqlDbType.VarChar, 20);
MyParams[2].SourceColumn = LastName;

From SqlDataAdapter Class:
The SqlDataAdapter, serves as a bridge between a DataSet and SQL
Server for retrieving and saving data.
In the scenario you described, there is no such need for a "bridge". You just use a SqlCommand, add the collection of SqlParameter to it, and then call ExecuteNonQuery() to perform the insert.
using(SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2"))
{
using(SqlCommand command = new SqlCommand(sql, connection))
{
try
{
connection.Open();
for (int i =0; i< gridView3.RowCount; i++)
{
SqlParameter parameter = new SqlParameter();
// TODO: handle name accordingly (MName, LName etc.)
parameter.ParameterName = "#FName";
// TODO: handle type accordingly
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
// TODO: use the field name accordingly
parameter.Value = Convert.ToString(gridView3.GetRowCellValue(i, "FieldName"));
// add the parameter to the command
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
}
catch(Exception)
{
// TODO: handle the exception
}
}
}
Remark: you should dispose your SQL related objects in the code - a convenient way to do that is to use using statements.

Related

INSERT from DataGridView in DB

my code only passes the first row to the database.
I am new to .NET. Who can suggest the problem.
for(int i = 0; i < dgvCSV_Datei.Rows.Count; i++)
{
var strQuery = "INSERT INTO Mobile (Name, IMEI, Hersteller) VALUES (#Name, #IMEI, #Hersteller)";
sqlCommand.CommandText = strQuery;
sqlCommand.Parameters.AddWithValue("#Name", dgvCSV_Datei.Rows[i].Cells[0].Value);
sqlCommand.Parameters.AddWithValue("#IMEI", dgvCSV_Datei.Rows[i].Cells[1].Value);
sqlCommand.Parameters.AddWithValue("#Hersteller", dgvCSV_Datei.Rows[i].Cells[2].Value);
sqlCommand.ExecuteNonQuery();
}
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
Your issue seems to be that you keep adding more parameters with the same name, without removing or changing the previous ones. Your code should instead look like this
const string strQuery = #"
INSERT INTO Mobile (Name, IMEI, Hersteller)
VALUES (#Name, #IMEI, #Hersteller);
";
using (var sqlConnection = new SqlConnection(YourConnString))
using (var sqlCommand = new SqlCommand(strQuery, sqlConnection))
{
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar, 100);
sqlCommand.Parameters.Add("#IMEI", SqlDbType.Varchar, 16);
sqlCommand.Parameters.Add("#Hersteller", SqlDbType.VarChar, 100);
sqlConnection.Open();
for(int i = 0; i < dgvCSV_Datei.Rows.Count; i++)
{
sqlCommand.Parameters["#Name"].Value = dgvCSV_Datei.Rows[i].Cells[0].Value;
sqlCommand.Parameters["#IMEI"].Value = dgvCSV_Datei.Rows[i].Cells[1].Value;
sqlCommand.Parameters["#Hersteller"].Value = dgvCSV_Datei.Rows[i].Cells[2].Value;
sqlCommand.ExecuteNonQuery();
}
}
A much better option is to use SqlBulkCopy. This is a highly performant bulk-copy mechanism specifically for plain inserts.
using (var bulk = new SqlBulkCopy(YourConnString, SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers))
{
bulk.DestinationTableName = "Mobile";
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[0].ColumnName, "Name");
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[1].ColumnName, "IMEI");
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[2].ColumnName, "Hersteller");
bulk.WriteToServer(dgvCSV_Datei);
}

ASP.NET:Update sql table row programmatically

I have a data conduit class where I want to create an update method that takes list of parameter names, their values and a stored procedure name. Up on execution, I want to update a particular row in sql db.
The code so far in data conduit class is:
public class clsDataConduit
{
SqlConnection Conn= new SqlConnection();
SqlDataReader rdr= null;
SqlDataAdapter dataChannel = new SqlDataAdapter();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
SqlCommand cmd = null;
List<SqlParameter> SQLParams = new List<SqlParameter>();
DataTable queryResults = new DataTable();
DataRow newRecord;
public void NewRecord(string SProcName)
{
//works fine
}
public void UpdateRecord(string SProcName)
{
Conn= new SqlConnection(connectionString);
//open the database
Conn.Open();
//initialise the command builder for this connection
SqlCommand dataCommand = new SqlCommand(SProcName, Conn);
//add the parameters to the command builder
//loop through each parameter
for (int Counter = 0; Counter < SQLParams.Count; Counter += 1)
{
//add it to the command builder
dataCommand.Parameters.Add(SQLParams[Counter]);
}
dataCommand.CommandType = CommandType.StoredProcedure;
dataChannel = new SqlDataAdapter(SProcName, Conn);
dataChannel.UpdateCommand = dataCommand;
commandBuilder = new SqlCommandBuilder(dataChannel);
dataChannel.Update(queryResults);
///////////////////////////////////////////////////////////
// Method runs fine till above code, BUT I am not too sure
// how to write the rest of the code so that It updates a
// a particular row in sql
///////////////////////////////////////////////////////////
//get the structure of a single record
//newRecord = queryResults.NewRow(); //from previous method - new data
Conn.Close();
}
}
I am not too sure how can I continue further from this point. If someone can help me out please.
Thanks
If I understand your code correctly, you have already filled the command with the appropriate parameters (with values already set), so you need only to call
dataCommand.ExecuteNonQuery();
This is all you need, (of course the SQLParams list should be already filled with the parameters and their values). Also, to be more generic, you could pass to the UpdateRecord, the list of SqlParameter to use for the storedprocedure called
public void UpdateRecord(string SProcName, List<SqlParameters> prms)
{
using(Conn= new SqlConnection(connectionString))
{
//open the database
Conn.Open();
//initialise the command builder for this connection
SqlCommand dataCommand = new SqlCommand(SProcName, Conn);
//add the parameters to the SqlCommand
dataCommand.Parameters.AddRange(prms.ToArray());
dataCommand.CommandType = CommandType.StoredProcedure;
dataCommand.ExecuteNonQuery();
}
}

update table in database from datatable

I load data from database table like this...
using (view_adapter = new SqlDataAdapter("select * from TVServiceProvider", connection_string))
{
using (dt = new DataTable())
{
view_adapter.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName.Substring(0, 2).Equals("id"))
dt.Columns[i].ReadOnly = false;
}
bs.DataSource = dt;
}
}
Where SqlDataAdapter view_adapter and DataTable dt. To apply changes to database I've created method
void View_Adapter_Click(object sender, EventArgs e)
{
try
{
view_adapter.Update(dt);
dt.AcceptChanges();
}
catch (Exception exc)
{
this.radLabelElement1.Text = exc.Message;
}
}
But when I click the button I've got an exception. It requires update command. Where and what command I should use?
You must create UpdateCommand and DeleteCommand for you view_adapter.
EDIT:
The code must look like this:
SqlDataAdapter view_adapter = new SqlDataAdapter();
view_adapter .SelectCommand = new SqlCommand(queryString, connection);
view_adapter .UpdateCommand = new SqlCommand(updateCommadString, connection);
view_adapter .DeleteCommand = new SqlCommand(deleteCommadString, connection);
using (SqlConnection connection = new SqlConnection(connectionString))
{
view_adapter.Fill(dt);
return dt;
}
Well, something is wrong or not clear in your code.
The view_adapter variable is initialized within a using block statement.
Thus, when exiting from the using block, the view_adatpter will be disposed by the framework and unusable in the click event. (like you have never called new to initialize it).
I suspect that you have another problem here. Using statement
A part from this, to automatically create the UpdateCommand, InsertCommand and DeleteCommand required to perform CRUD operations with a DataAdapter you could use a SqlCommandBuilder.
(This is possible only if you use one table in the select statement and that table has a primary key defined)
So to summarize everything:
string queryString = "select * from TVServiceProvider";
view_adapter = new SqlDataAdapter(queryString, connection_string);
SqlCommandBuilder builder = new SqlCommandBuilder(view_adapter)
builder.GetUpdateCommand(); // Force the building of commands
view_adapter.Fill(dt);
then your click event should works as is now.
This code is not related to yours, but may help you, If you give it a look. I got it from MSDN
public static SqlDataAdapter CreateCustomerAdapter(
SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();
// Create the SelectCommand.
SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
"WHERE Country = #Country AND City = #City", connection);
// Add the parameters for the SelectCommand.
command.Parameters.Add("#Country", SqlDbType.NVarChar, 15);
command.Parameters.Add("#City", SqlDbType.NVarChar, 15);
adapter.SelectCommand = command;
// Create the InsertCommand.
command = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (#CustomerID, #CompanyName)", connection);
// Add the parameters for the InsertCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
adapter.InsertCommand = command;
// Create the UpdateCommand.
command = new SqlCommand(
"UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName " +
"WHERE CustomerID = #oldCustomerID", connection);
// Add the parameters for the UpdateCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
SqlParameter parameter = command.Parameters.Add(
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.UpdateCommand = command;
// Create the DeleteCommand.
command = new SqlCommand(
"DELETE FROM Customers WHERE CustomerID = #CustomerID", connection);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add(
"#CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
return adapter;
}
What actually worked for me from Steve and Hamlet's suggestions is the following. I had one hiccup because I tried to do an accept changes on my rows and table before doing the view adapter update. The accept changes in only needed to save the changes to the datatable before reusing the datatable for displaying in a gridview or other operations.
SqlDataAdapter viewAdapter = new SqlDataAdapter("Select * From Users", DBConn);
SqlCommandBuilder builder = new SqlCommandBuilder(viewAdapter);
viewAdapter.UpdateCommand = builder.GetUpdateCommand();
DataTable Users = new DataTable();
viewAdapter.Fill(Users);
foreach (DataRow user in Users.Rows)
{
foreach (DataColumn c in Users.Columns)
{
Console.WriteLine(c.ColumnName);
if (c.DataType != typeof(DateTime))
{
// Clean up empty space around field entries
user[c.ColumnName] = user[c.ColumnName].ToString().Trim();
}
}
// user.AcceptChanges();
// Do not do an accept changes for either the table or the row before your ViewAdapter Update.
// It will appear as though you do not have changes to push.
}
// Users.AcceptChanges();
viewAdapter.Update(Users);

Grab SQL variables that changes in query in ADO.NET

How do I get variable #Test that was changed in query?
const string query = #"SET #Test = 2;";
using (var connection = new SqlConnection(conStr))
{
connection.Open();
var command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#Test", 1);
var r = command.ExecuteReader();
// command.Parameters["#Test"].Value == 1
// r hasn't any variables
}
ADDED:
I've solve this problem withoute creating stored procedure
const string query = #"SET #Test = 2;";
using (var connection = new SqlConnection(conStr))
{
connection.Open();
var command = new SqlCommand(query, connection);
SqlParameter par = command.Parameters.Add("#Test", SqlDbType.NVarChar, 15);
par.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
// par.Value now contain 2
}
Both ansvers help!
Firstly, in your stored procedure the parameter needs to be marked as OUTPUT
CREATE PROC MyQuery
#Test INT OUTPUT
AS
SET #Test = 2
Then, when constructing the c# code, instead of using AddWithValue, be more explicit in your creation of a SqlParameter, namely marking it as Input/Output.
var command = new SqlCommand("MyQuery", connection);
command.CommandType = CommandType.StoredProcedure;
var param = command.CreateParameter();
param.Name = "#Test";
param.Type = DbType.Int;
param.Direction = ParameterDirection.InputOutput;
param.Value = 1;
Now once you execute your command:
command.ExecuteNonQuery(); // Could also be ExecuteReader, if you have a resultset too!
You can read the value of param, which should have changed to 2
if(param.Value == 2)
{ Console.WriteLine("WooHoo"); }

How to execute a stored procedure within C# program

I want to execute this stored procedure from a C# program.
I have written the following stored procedure in a SqlServer query window and saved it as
stored1:
use master
go
create procedure dbo.test as
DECLARE #command as varchar(1000), #i int
SET #i = 0
WHILE #i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),#i)
EXEC(#command)
SET #i = #i + 1
END
EDITED:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
Console.WriteLine("\nTop 10 Most Expensive Products:\n");
try
{
conn = new SqlConnection("Server=(local);DataBase=master;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.test", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
/*while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-25} Price: ${1,6:####.00}",
rdr["TenMostExpensiveProducts"],
rdr["UnitPrice"]);
}*/
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Program p= new Program();
p.RunStoredProc();
Console.Read();
}
}
}
This displays the exception Cannot find the stored procedure dbo.test. Do I need to provide the path? If yes, in which location should the stored procedures be stored?
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
}
using (SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI")) {
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
}
}
}
Here are some interesting links you could read:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
http://www.c-sharpcorner.com/UploadFile/dclark/InsOutsinCS11302005072332AM/InsOutsinCS.aspx
http://www.codeproject.com/KB/cs/simplecodeasp.aspx
http://msdn.microsoft.com/en-us/library/ms171921(VS.80).aspx
Calling stored procedure in C#:
SqlCommand cmd = new SqlCommand("StoredProcedureName",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#value",txtValue.Text);
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
}}
This is code for executing stored procedures with and with out parameters via reflection.
Do note that the objects property names need to match the parameters of the stored procedure.
private static string ConnString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
private SqlConnection Conn = new SqlConnection(ConnString);
public void ExecuteStoredProcedure(string procedureName)
{
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
public void ExecuteStoredProcedure(string procedureName, object model)
{
var parameters = GenerateSQLParameters(model);
SqlConnection sqlConnObj = new SqlConnection(ConnString);
SqlCommand sqlCmd = new SqlCommand(procedureName, sqlConnObj);
sqlCmd.CommandType = CommandType.StoredProcedure;
foreach (var param in parameters)
{
sqlCmd.Parameters.Add(param);
}
sqlConnObj.Open();
sqlCmd.ExecuteNonQuery();
sqlConnObj.Close();
}
private List<SqlParameter> GenerateSQLParameters(object model)
{
var paramList = new List<SqlParameter>();
Type modelType = model.GetType();
var properties = modelType.GetProperties();
foreach (var property in properties)
{
if (property.GetValue(model) == null)
{
paramList.Add(new SqlParameter(property.Name, DBNull.Value));
}
else
{
paramList.Add(new SqlParameter(property.Name, property.GetValue(model)));
}
}
return paramList;
}
SqlConnection conn = null;
SqlDataReader rdr = null;
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand("CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}
By using Ado.net
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace PBDataAccess
{
public class AddContact
{
// for preparing connection to sql server database
private SqlConnection conn;
// for preparing sql statement or stored procedure that
// we want to execute on database server
private SqlCommand cmd;
// used for storing the result in datatable, basically
// dataset is collection of datatable
private DataSet ds;
// datatable just for storing single table
private DataTable dt;
// data adapter we use it to manage the flow of data
// from sql server to dataset and after fill the data
// inside dataset using fill() method
private SqlDataAdapter da;
// created a method, which will return the dataset
public DataSet GetAllContactType()
{
// retrieving the connection string from web.config, which will
// tell where our database is located and on which database we want
// to perform opearation, in this case we are working on stored
// procedure so you might have created it somewhere in your database.
// connection string will include the name of the datasource, your
// database name, user name and password.
using (conn = new SqlConnection(ConfigurationManager.ConnectionString["conn"]
.ConnectionString))
{
// Addcontact is the name of the stored procedure
using (cmd = new SqlCommand("Addcontact", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// here we are passing the parameters that
// Addcontact stored procedure expect.
cmd.Parameters.Add("#CommandType",
SqlDbType.VarChar, 50).Value = "GetAllContactType";
// here created the instance of SqlDataAdapter
// class and passed cmd object in it
da = new SqlDataAdapter(cmd);
// created the dataset object
ds = new DataSet();
// fill the dataset and your result will be
stored in dataset
da.Fill(ds);
}
}
return ds;
}
}
****** Stored Procedure ******
CREATE PROCEDURE Addcontact
#CommandType VARCHAR(MAX) = NULL
AS
BEGIN
IF (#CommandType = 'GetAllContactType')
BEGIN
SELECT * FROM Contacts
END
END
this is an example of a stored procedure that returns a value and it's execution in c#
CREATE PROCEDURE [dbo].[InsertPerson]
-- Add the parameters for the stored procedure here
#FirstName nvarchar(50),#LastName nvarchar(50),
#PersonID int output
AS
BEGIN
insert [dbo].[Person](LastName,FirstName) Values(#LastName,#FirstName)
set #PersonID=SCOPE_IDENTITY()
END
Go
--------------
// Using stored procedure in adapter to insert new rows and update the identity value.
static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) {
String commandText = "dbo.InsertPerson";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn);
mySchool.InsertCommand = new SqlCommand(commandText, conn);
mySchool.InsertCommand.CommandType = CommandType.StoredProcedure;
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("#FirstName", SqlDbType.NVarChar, 50, "FirstName"));
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("#LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("#PersonID", SqlDbType.Int, 0, "PersonID"));
personId.Direction = ParameterDirection.Output;
DataTable persons = new DataTable();
mySchool.Fill(persons);
DataRow newPerson = persons.NewRow();
newPerson["FirstName"] = firstName;
newPerson["LastName"] = lastName;
persons.Rows.Add(newPerson);
mySchool.Update(persons);
Console.WriteLine("Show all persons:");
ShowDataTable(persons, 14);
Using Dapper. so i added this i hope anyone help.
public void Insert(ProductName obj)
{
SqlConnection connection = new SqlConnection(Connection.GetConnectionString());
connection.Open();
connection.Execute("ProductName_sp", new
{ #Name = obj.Name, #Code = obj.Code, #CategoryId = obj.CategoryId, #CompanyId = obj.CompanyId, #ReorderLebel = obj.ReorderLebel, #logo = obj.logo,#Status=obj.Status, #ProductPrice = obj.ProductPrice,
#SellingPrice = obj.SellingPrice, #VatPercent = obj.VatPercent, #Description=obj.Description, #ColourId = obj.ColourId, #SizeId = obj.SizeId,
#BrandId = obj.BrandId, #DisCountPercent = obj.DisCountPercent, #CreateById =obj.CreateById, #StatementType = "Create" }, commandType: CommandType.StoredProcedure);
connection.Close();
}
No Dapper answer here. So I added one
using Dapper;
using System.Data.SqlClient;
using (var cn = new SqlConnection(#"Server=(local);DataBase=master;Integrated Security=SSPI"))
cn.Execute("dbo.test", commandType: CommandType.StoredProcedure);
Please check out Crane (I'm the author)
https://www.nuget.org/packages/Crane/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
var result = sqlAccess.Command().ExecuteNonQuery("StoredProcedureName");
Also has a bunch of other features you might like.
You mean that your code is DDL?
If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure
CommandType = CommandType.Text
Most Simple and straight forward..
SqlCommand cmd = new SqlCommand("StoredProcedureName",con); // Just like you declared it
cmd.CommandType = CommandType.StoredProcedure; // an attribute related to the object
cmd.Parameters.AddWithValue("#value",txtValue.Text); // Parameter name and text source
con.Open();
int rowAffected = cmd.ExecuteNonQuery();
con.Close();
What I made, in my case I wanted to show procedure's result in dataGridView:
using (var command = new SqlCommand("ProcedureNameHere", connection) {
// Set command type and add Parameters
CommandType = CommandType.StoredProcedure,
Parameters = { new SqlParameter("#parameterName",parameterValue) }
})
{
// Execute command in Adapter and store to dataset
var adapter = new SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
// Display results in DatagridView
dataGridView1.DataSource = dataset.Tables[0];
}

Categories

Resources