im trying to update my database table with a dataset. I have a local excel file that can be edited and imported into a dataset. Then i want to use this dataset with the updated data to update my database table. This is my code:
public void UpdateDatabase(DataSet data, string tableName)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestDbOnBrie"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.TransportSchedule_Customer;", connection))
{
SqlCommand selectCmd = new SqlCommand("SELECT * FROM dbo.TransportSchedule_Customer", connection);
adapter.SelectCommand = selectCmd;
SqlCommand updateCmd = new SqlCommand("UPDATE dbo.TransportSchedule_Customer SET Alias=#Alias, DeliveryDays1=#DeliveryDays1, DeliveryHours1=#DeliveryHours1, DeliveryType1=#DeliveryType1, DeliveryDays2=#DeliveryDays2, DeliveryHours2=#DeliveryHours2, DeliveryType2=#DeliveryType2, DeliveryDays3=#DeliveryDays3, DeliveryHours3=#DeliveryHours3, DeliveryType3=#DeliveryType3, DistanceToDealer=#DistanceToDealer WHERE AdrID=#AdrID AND CustID=#CustID", connection);
SqlCommand insertCmd = new SqlCommand("INSERT INTO dbo.TransportSchedule_Customer (CustID, Alias, AdrID, DeliveryDays1, DeliveryHours1, DeliveryType1, DeliveryDays2, DeliveryHours2, DeliveryType2, DeliveryDays3, DeliveryHours3, DeliveryType3, DistanceToDealer)" +
"VALUES (#CustID, #Alias, #AdrID, #DeliveryDays1, #DeliveryHours1, #DeliveryType1, #DeliveryDays2, #DeliveryHours2, #DeliveryType2, #DeliveryDays3, #DeliveryHours3, #DeliveryType3, #DistanceToDealer)", connection);
//insertCmd.Parameters.Add("#CustID", SqlDbType.VarChar, 50, "CustID");
//insertCmd.Parameters.Add("#AdrID", SqlDbType.Int, 50, "AdrID");
//insertCmd.Parameters.Add("#Alias", SqlDbType.VarChar, 50, "Alias");
//insertCmd.Parameters.Add("#DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
//insertCmd.Parameters.Add("#DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
//insertCmd.Parameters.Add("#DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");
//insertCmd.Parameters.Add("#DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
//insertCmd.Parameters.Add("#DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
//insertCmd.Parameters.Add("#DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");
//insertCmd.Parameters.Add("#DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
//insertCmd.Parameters.Add("#DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
//insertCmd.Parameters.Add("#DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");
//insertCmd.Parameters.Add("#DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");
//adapter.InsertCommand = insertCmd;
updateCmd.Parameters.Add("#CustID", SqlDbType.VarChar, 50, "CustID");
updateCmd.Parameters.Add("#AdrID", SqlDbType.Int, 50, "AdrID");
updateCmd.Parameters.Add("#Alias", SqlDbType.VarChar, 50, "Alias");
updateCmd.Parameters.Add("#DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
updateCmd.Parameters.Add("#DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
updateCmd.Parameters.Add("#DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");
updateCmd.Parameters.Add("#DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
updateCmd.Parameters.Add("#DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
updateCmd.Parameters.Add("#DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");
updateCmd.Parameters.Add("#DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
updateCmd.Parameters.Add("#DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
updateCmd.Parameters.Add("#DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");
updateCmd.Parameters.Add("#DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");
adapter.UpdateCommand = updateCmd;
adapter.Update(data, "1");
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in UpdateDatabase() method. Error Message : " + exception.Message);
}
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
}
My problem is that when i ONLY use the update command i get this error:
Update requires a valid InsertCommand when passed DataRow collection with new rows.
When i use both the update command and the Insert command i get this error:
Violation of PRIMARY KEY constraint 'PK_TransportSchedule_Customer'. Cannot insert duplicate key in object 'dbo.TransportSchedule_Customer'.
I'm thinking that it thinks the dataset table-rows are new rows and has to be inserted, but they are actually not. The rows exist the database and ONLY some of them are updated.
doe's anyone have any ideas of what to do?
Well i found out how to do this myself. here is how my method turned out. And this works perfect. It only updates the rows that exists and has different data in the file Dataset and the Dataset from the database.
My Method:
public void UpdateDatabase(DataSet data, string custID)
{
DataTable fromdatabase = new DataTable();
DataTable fromFile = data.Tables[0];
string connectionString = ConfigurationManager.ConnectionStrings["TestDbOnBrie"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * FROM dbo.TransportSchedule_Customer WHERE CustID = '" + custID + "';";
SqlCommand command = new SqlCommand(sqlCmd, connection);
using (SqlCommand updateCmd = new SqlCommand("UPDATE dbo.TransportSchedule_Customer SET DeliveryDays1=#DeliveryDays1, DeliveryHours1=#DeliveryHours1, DeliveryType1=#DeliveryType1, DeliveryDays2=#DeliveryDays2, DeliveryHours2=#DeliveryHours2, DeliveryType2=#DeliveryType2, DeliveryDays3=#DeliveryDays3, DeliveryHours3=#DeliveryHours3, DeliveryType3=#DeliveryType3, DistanceToDealer=#DistanceToDealer WHERE Alias=#Alias AND CustID=#CustID", connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.UpdateCommand = updateCmd;
adapter.Fill(fromdatabase);
updateCmd.Parameters.Add("#CustID", SqlDbType.VarChar, 50, "CustID");
updateCmd.Parameters.Add("#Alias", SqlDbType.VarChar, 50, "Alias");
updateCmd.Parameters.Add("#DeliveryDays1", SqlDbType.VarChar, 50, "DeliveryDays1");
updateCmd.Parameters.Add("#DeliveryHours1", SqlDbType.VarChar, 50, "DeliveryHours1");
updateCmd.Parameters.Add("#DeliveryType1", SqlDbType.VarChar, 50, "DeliveryType1");
updateCmd.Parameters.Add("#DeliveryDays2", SqlDbType.VarChar, 50, "DeliveryDays2");
updateCmd.Parameters.Add("#DeliveryHours2", SqlDbType.VarChar, 50, "DeliveryHours2");
updateCmd.Parameters.Add("#DeliveryType2", SqlDbType.VarChar, 50, "DeliveryType2");
updateCmd.Parameters.Add("#DeliveryDays3", SqlDbType.VarChar, 50, "DeliveryDays3");
updateCmd.Parameters.Add("#DeliveryHours3", SqlDbType.VarChar, 50, "DeliveryHours3");
updateCmd.Parameters.Add("#DeliveryType3", SqlDbType.VarChar, 50, "DeliveryType3");
updateCmd.Parameters.Add("#DistanceToDealer", SqlDbType.VarChar, 50, "DistanceToDealer");
for (int i = 0; i < fromdatabase.Rows.Count; i++)
{
int Resultcompare = 0;
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays1"].ToString(), fromFile.Rows[i]["DeliveryDays1"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours1"].ToString(), fromFile.Rows[i]["DeliveryHours1"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType1"].ToString(), fromFile.Rows[i]["DeliveryType1"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays2"].ToString(), fromFile.Rows[i]["DeliveryDays2"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours2"].ToString(), fromFile.Rows[i]["DeliveryHours2"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType2"].ToString(), fromFile.Rows[i]["DeliveryType2"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryDays3"].ToString(), fromFile.Rows[i]["DeliveryDays3"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryHours3"].ToString(), fromFile.Rows[i]["DeliveryHours3"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DeliveryType3"].ToString(), fromFile.Rows[i]["DeliveryType3"].ToString());
Resultcompare += string.Compare(fromdatabase.Rows[i]["DistanceToDealer"].ToString(), fromFile.Rows[i]["DistanceToDealer"].ToString());
if (Resultcompare == 0)
{
//do nothing
}
else
{
fromdatabase.Rows[i]["DeliveryDays1"] = fromFile.Rows[i]["DeliveryDays1"];
fromdatabase.Rows[i]["DeliveryHours1"] = fromFile.Rows[i]["DeliveryHours1"];
fromdatabase.Rows[i]["DeliveryType1"] = fromFile.Rows[i]["DeliveryType1"];
fromdatabase.Rows[i]["DeliveryDays2"] = fromFile.Rows[i]["DeliveryDays2"];
fromdatabase.Rows[i]["DeliveryHours2"] = fromFile.Rows[i]["DeliveryHours2"];
fromdatabase.Rows[i]["DeliveryType2"] = fromFile.Rows[i]["DeliveryType2"];
fromdatabase.Rows[i]["DeliveryDays3"] = fromFile.Rows[i]["DeliveryDays3"];
fromdatabase.Rows[i]["DeliveryHours3"] = fromFile.Rows[i]["DeliveryHours3"];
fromdatabase.Rows[i]["DeliveryType3"] = fromFile.Rows[i]["DeliveryType3"];
fromdatabase.Rows[i]["DistanceToDealer"] = fromFile.Rows[i]["DistanceToDealer"];
adapter.Update(fromdatabase);
}
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in UpdateDatabase() method. Error Message : " + exception.Message);
}
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
}
if u need help just comment.
Related
i'm working to my lending management system and I want to add data from my database coming to two different windows form.
here's my code to the first windows form.
private void button1_Click(object sender, EventArgs e)
{
if (RequiredEntry() == true)
{
return;
}
try
{
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-79MM8LM;Initial Catalog=lend;Integrated Security=True");
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
cn.Open();
//if (textBox13.Text.Trim() != textBox26.Text.Trim())
if (textBox13. Text != textBox26.Text)
{
string sSQL = "insert into costumerinfo(name,address,contactNo,occupation,occupationAddress,salary,birthDate,birthPlace,workYears,civilStatus,gender,age,cmName,cmAge,cmAddress,cmContactNo,cmOccupation,cmOccupatioAdd,cmSalary,cm_Name,cm_Age,cm_Address,cm_ContactNo,cm_Occupation,cm_OccupationAdd,cm_Salary) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8,#d9,#d10,#d11,#d12,#d13,#d14,#d15,#d16,#d17,#d18,#d19,#d20,#d21,#d22,#d23,#d24,#25,#26)";
SqlCommand cmd = new SqlCommand(sSQL, cn);
//new client
;
SqlParameter name = new SqlParameter("#d1", SqlDbType.Char, 10);
name.Value = textBox1.Text.ToString();
cmd.Parameters.Add(name);
SqlParameter address = new SqlParameter("#d2", SqlDbType.VarChar, 50);
address.Value = textBox2.Text.ToString();
cmd.Parameters.Add(address);
SqlParameter contactNo = new SqlParameter("#d3", SqlDbType.Char, 10);
contactNo.Value = textBox3.Text.ToString();
cmd.Parameters.Add(contactNo);
SqlParameter occupation = new SqlParameter("#d4", SqlDbType.Char, 50);
occupation.Value = textBox4.Text.ToString();
cmd.Parameters.Add(occupation);
SqlParameter occupationAddress = new SqlParameter("#d5", SqlDbType.VarChar, 50);
occupationAddress.Value = textBox5.Text.ToString();
cmd.Parameters.Add(occupationAddress);
SqlParameter salary = new SqlParameter("#d6", SqlDbType.Char, 10);
salary.Value = textBox6.Text.ToString();
cmd.Parameters.Add(salary);
SqlParameter birthDate = new SqlParameter("#d7", SqlDbType.VarChar, 10);
birthDate.Value = maskedTextBox1.Text.ToString();
cmd.Parameters.Add(birthDate);
SqlParameter birthPlace = new SqlParameter("#d8", SqlDbType.Char, 50);
birthPlace.Value = textBox8.Text.ToString();
cmd.Parameters.Add(birthPlace);
SqlParameter workYears = new SqlParameter("#d9", SqlDbType.Char, 2);
workYears.Value = textBox9.Text.ToString();
cmd.Parameters.Add(workYears);
SqlParameter civilStatus = new SqlParameter("#d10", SqlDbType.Char, 10);
civilStatus.Value = comboBox1.Text.ToString();
cmd.Parameters.Add(civilStatus);
SqlParameter gender = new SqlParameter("#d11", SqlDbType.Char, 10);
gender.Value = comboBox2.Text.ToString();
cmd.Parameters.Add(gender);
SqlParameter age = new SqlParameter("#d12", SqlDbType.Char, 2);
age.Value = textBox12.Text.ToString();
cmd.Parameters.Add(age);
//co-maker 1
SqlParameter cmName = new SqlParameter("#d13", SqlDbType.Char, 2);
cmName.Value = textBox13.Text.ToString();
cmd.Parameters.Add(cmName);
SqlParameter cmAge = new SqlParameter("#d14", SqlDbType.VarChar, 50);
cmAge.Value = textBox14.Text.ToString();
cmd.Parameters.Add(cmAge);
SqlParameter cmAddress = new SqlParameter("#d15", SqlDbType.VarChar, 50);
cmAddress.Value = textBox15.Text.ToString();
cmd.Parameters.Add(cmAddress);
SqlParameter cmContactNo = new SqlParameter("#d16", SqlDbType.VarChar, 10);
cmContactNo.Value = textBox16.Text.ToString();
cmd.Parameters.Add(cmContactNo);
SqlParameter cmOccupation = new SqlParameter("#d17", SqlDbType.Char, 20);
cmOccupation.Value = textBox17.Text.ToString();
cmd.Parameters.Add(cmOccupation);
SqlParameter cmOccupatioAdd = new SqlParameter("#d18", SqlDbType.VarChar, 50);
cmOccupatioAdd.Value = textBox18.Text.ToString();
cmd.Parameters.Add(cmOccupatioAdd);
SqlParameter cmSalary = new SqlParameter("#d19", SqlDbType.VarChar, 10);
cmSalary.Value = textBox19.Text.ToString();
cmd.Parameters.Add(cmSalary);
//co-maker 2
SqlParameter cm_Name = new SqlParameter("#d20", SqlDbType.Char, 10);
cm_Name.Value = textBox26.Text.ToString();
cmd.Parameters.Add(cm_Name);
SqlParameter cm_Age = new SqlParameter("#d21", SqlDbType.VarChar, 10);
cm_Age.Value = textBox25.Text.ToString();
cmd.Parameters.Add(cm_Age);
SqlParameter cm_Address = new SqlParameter("#d22", SqlDbType.VarChar, 50);
cm_Address.Value = textBox23.Text.ToString();
cmd.Parameters.Add(cm_Address);
SqlParameter cm_ContactNo = new SqlParameter("#d23", SqlDbType.VarChar, 20);
cm_ContactNo.Value = textBox24.Text.ToString();
cmd.Parameters.Add(cm_ContactNo);
SqlParameter cm_Occupation = new SqlParameter("#d24", SqlDbType.VarChar, 50);
cm_Occupation.Value = textBox22.Text.ToString();
cmd.Parameters.Add(cm_Occupation);
SqlParameter cm_OccupationAdd = new SqlParameter("#d25", SqlDbType.VarChar, 50);
cm_OccupationAdd.Value = textBox21.Text.ToString();
cmd.Parameters.AddWithValue("#25", textBox21.Text);
//cmd.Parameters.Add(cm_OccupationAdd);
SqlParameter cm_Salary = new SqlParameter("#d26", SqlDbType.VarChar, 2);
cm_Salary.Value = textBox20.Text.ToString();
cmd.Parameters.AddWithValue("#26", textBox20.Text);
//cmd.Parameters.Add(cm_Salary);
int temp = 0;
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
cn.Close();
MessageBox.Show("New client added Successfully!");
}
else
{
MessageBox.Show("data not added!");
return;
}
}
else
{`enter code here`
MessageBox.Show("Name of two Co-Maker are the same", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Data Error");
return;
}
}
and here my second windows form
private void button1_Click(object sender, EventArgs e)
{
if (RequiredEntry() == true)
{
return;
}
try
{
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-79MM8LM;Initial Catalog=lend;Integrated Security=True");
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
cn.Open();
//if (textBox13.Text.Trim() != textBox26.Text.Trim())
if (String.IsNullOrEmpty(comboBox1.Text))
{
string sSQL = "insert into costumerinfo(name, amount, interest, daysOfPayment, payPerDay, totalAmount, processingFee, insurance, notarial) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8)";
SqlCommand cmd = new SqlCommand(sSQL, cn);
//new client
//SqlParameter clientID = new SqlParameter("#d1", SqlDbType.Char, 10);
//clientID.Value = textBox1.Text.ToString();
//cmd.Parameters.Add(clientID);
SqlParameter name = new SqlParameter("#d1", SqlDbType.Char, 10);
name.Value = comboBox1.Text.ToString();
cmd.Parameters.Add(name);
SqlParameter amount = new SqlParameter("#d2", SqlDbType.VarChar, 50);
amount.Value = textBox2.Text.ToString();
cmd.Parameters.Add(amount);
SqlParameter interest = new SqlParameter("#d3", SqlDbType.Char, 10);
interest.Value = textBox3.Text.ToString();
cmd.Parameters.Add(interest);
SqlParameter daysOfPayment = new SqlParameter("#d4", SqlDbType.Char, 50);
daysOfPayment.Value = textBox4.Text.ToString();
cmd.Parameters.Add(daysOfPayment);
SqlParameter payPerDay = new SqlParameter("#d5", SqlDbType.VarChar, 50);
payPerDay.Value = label10.Text.ToString();
cmd.Parameters.Add(payPerDay);
SqlParameter totalAmount = new SqlParameter("#d6", SqlDbType.VarChar, 50);
totalAmount.Value = label11.Text.ToString();
cmd.Parameters.Add(totalAmount);
SqlParameter processingFee = new SqlParameter("#d7", SqlDbType.Char, 10);
processingFee.Value = textBox7.Text.ToString();
cmd.Parameters.Add(processingFee);
SqlParameter insurance = new SqlParameter("#d8", SqlDbType.VarChar, 10);
insurance.Value = textBox8.Text.ToString();
cmd.Parameters.Add(insurance);
SqlParameter notarial = new SqlParameter("#d9", SqlDbType.Char, 50);
notarial.Value = textBox9.Text.ToString();
cmd.Parameters.Add(notarial);
int temp = 0;
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
cn.Close();
MessageBox.Show("New transaction added Successfully!");
}
else
{
MessageBox.Show("data not added!");
return;
}
}
else
{
MessageBox.Show("Name of two Co-Maker are the same", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Data Error");
return;
}
}
but here I got in my database
[the new data was adding but create new line][1]
[i want to add data align with name][2]
[1]: https://i.stack.imgur.com/B6Gb2.png
[2]: https://i.stack.imgur.com/QaLov.png
can you help me thanks
What you want, is to insert from one and update from the other.
SQL insert command -> The INSERT INTO statement is used to insert new records in a table.
SQL update command -> The UPDATE statement is used to modify the existing records in a table.
So your algorithm should be something like this:
Select from the table to see if the row exists
select * from costumerinfo where name = #name
If it does not exist, then insert
insert into costumerinfo
If it does exist, update the relevant values
update customerinfo set ... where name = #name
You can of course change the second form and directly call
string sSQL = "update costumerinfo set amount=#d1, interest=#d2, daysOfPayment = #d3, payPerDay = #d4, totalAmount= $d5, processingFee=#d6, insurance #d7, notarial #d8) values(#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8) where name = name=#d9";
Trying to insert a collection into a table in SQL Server 2014. Here's my code it executes without error but when I check my table - nothing is added. My collection object orders isn't empty either I can see it has 3 members when debugging it.
IEnumerable<CompleteOrderDetails> orders;
JoinDetails(doc, ns, xmlFragment1, out orders);
string connectionstring = null;
SqlConnection conn;
connectionstring = "Data Source = DANNY; Initial Catalog = Alliance; Integrated Security = SSPI";
using (conn = new SqlConnection(connectionstring))
{
string customerInsert = "INSERT INTO AmazonCustomer (AddressLine1, AddressLine2, AddressLine3, City, StateOrRegion, AmazonOrderId, PostalCode, Title, ItemPrice, ShippingPrice, Quantity) " +
"VALUES (#AddressLine1, #AddressLine2, #AddressLine3, #City, #StateOrRegion, #AmazonOrderId, #PostalCode, #Title, #ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
foreach (var order in orders)
{
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150).Value = order.AmazonOrderId;
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150).Value = order.Name;
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150).Value = order.AddressLine1;
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150).Value = order.AddressLine2;
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150).Value = order.AddressLine3;
query.Parameters.Add("#City", SqlDbType.NVarChar, 150).Value = order.City;
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150).Value = order.StateOrRegion;
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150).Value = order.PostalCode;
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150).Value = order.Title;
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150).Value = order.ItemPrice;
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150).Value = order.ShippingPrice;
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150).Value = order.Quantity;
}
conn.Open();
conn.Close();
}
}
Code Edits from Comments
private static void ExecuteSqlTransaction(IEnumerable<CompleteOrderDetails> orders)
{
string connectionstring = null;
SqlConnection conn;
SqlTransaction transaction;
connectionstring = "Data Source = DANNY; Initial Catalog = Alliance; Integrated Security = SSPI";
using (conn = new SqlConnection(connectionstring))
{
conn.Open();
transaction = conn.BeginTransaction("Transaction");
string customerInsert =
"INSERT INTO AmazonCustomer (Name, AddressLine1, AddressLine2, AddressLine3, City, StateOrRegion, AmazonOrderId, PostalCode, Title, ItemPrice, ShippingPrice, Quantity) VALUES (#Name, #AddressLine1, #AddressLine2, #AddressLine3, #City, #StateOrRegion, #AmazonOrderId, #PostalCode, #Title, #ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
query.Transaction = transaction;
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
try
{
foreach (var order in orders)
{
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId ?? Convert.DBNull;
query.Parameters["#Name"].Value = order.Name ?? Convert.DBNull;
query.Parameters["#AddressLine1"].Value = order.AddressLine1 ?? Convert.DBNull;
query.Parameters["#AddressLine2"].Value = order.AddressLine2 ?? Convert.DBNull;
query.Parameters["#AddressLine3"].Value = order.AddressLine3 ?? Convert.DBNull;
query.Parameters["#City"].Value = order.City ?? Convert.DBNull;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion ?? Convert.DBNull;
query.Parameters["#PostalCode"].Value = order.PostalCode ?? Convert.DBNull;
query.Parameters["#Title"].Value = order.Title ?? Convert.DBNull;
query.Parameters["#ItemPrice"].Value = order.ItemPrice ?? Convert.DBNull;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice ?? Convert.DBNull;
query.Parameters["#Quantity"].Value = order.Quantity ?? Convert.DBNull;
query.ExecuteNonQuery();
transaction.Commit();
}
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}
You open and close the connection without actually executing anything.
Also, move the adding of the parameters outside of your foreach loop and just set the values within the loop.
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
conn.Open();
foreach (var order in orders)
{
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId;
query.Parameters["#Name"].Value = order.Name;
query.Parameters["#AddressLine1"].Value = order.AddressLine1;
query.Parameters["#AddressLine2"].Value = order.AddressLine2;
query.Parameters["#AddressLine3"].Value = order.AddressLine3;
query.Parameters["#City"].Value = order.City;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion;
query.Parameters["#PostalCode"].Value = order.PostalCode;
query.Parameters["#Title"].Value = order.Title;
query.Parameters["#ItemPrice"].Value = order.ItemPrice;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice;
query.Parameters["#Quantity"].Value = order.Quantity;
query.ExecuteNonQuery();
}
conn.Close();
}
Apart from the obvious error of the missing ExecuteNonQuery call, your code will fail again because you add the parameters at each loop. This will lead to an exception caused by a parameter already defined.
You need to clear the parameters collection with
cmd.Parameters.Clear();
at the start of each loop or better define the parameters before the loop and, inside the loop, change only the values
using (conn = new SqlConnection(connectionstring))
{
string customerInsert = #"INSERT INTO AmazonCustomer
(AddressLine1, AddressLine2, AddressLine3, City,
StateOrRegion, AmazonOrderId, PostalCode, Title,
ItemPrice, ShippingPrice, Quantity)
VALUES (#AddressLine1, #AddressLine2, #AddressLine3, #City,
#StateOrRegion, #AmazonOrderId, #PostalCode, #Title,
#ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
// Not used ???
// query.Parameters.Add("#Name", SqlDbType.NVarChar, 150)
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
conn.Open();
using(SqlTransaction tr = conn.BeginTransaction())
{
foreach (var order in orders)
{
// Not used ???
// query.Parameters["#Name"].Value = order.Name;
query.Parameters["#AddressLine1"].Value = order.AddressLine1;
query.Parameters["#AddressLine2"].Value = order.AddressLine2;
query.Parameters["#AddressLine3"].Value = order.AddressLine3;
query.Parameters["#City"].Value = order.City;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion;
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId;
query.Parameters["#PostalCode"].Value = order.PostalCode;
query.Parameters["#Title"].Value = order.Title;
query.Parameters["#ItemPrice"].Value = order.ItemPrice;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice;
query.Parameters["#Quantity"].Value = order.Quantity;
query.ExecuteNonQuery();
}
tr.Commit();
}
}
}
Notice that the connection could be opened at the start of the loop and not at each loop, while the using statement take cares to close and dispose it, and given the nature of your inserts, I suggest also to encapsulate everything inside a SqlTransaction so your code is more 'atomic'.
Finally something is not correct in your query, there is a parameter placeholder that has not matching parameter in the collection (#ID) and there is a parameter that has no placeholder in the query (#name). Without fixing these two errors you get other errors. I have removed them from the query and from the parameters collection
This is my aspx.cs page,these codes should insert the values into the database,but presently its not going good,its not inserting into database,i am not getting any errors but insertion is not happening,i have no idea what is going wrong.IS there an possibility of SqlException? or any other issues?
protected void btnSkipSubmit_Click(object sender, EventArgs e)
{
int random = 0;
bool isValidInt = int.TryParse(txtrandom.Text, out random);
//string dummmy = "D";
//int dum = 0;
Patient p = new Patient();
//PatientBill pb = new PatientBill();
myConnection obj1 = new myConnection();
DateTime sdt = DateTime.Now;
// string a;
string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
string cmdString = "";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(cmdString, con);
SqlTransaction transaction;
if (isValidInt)
{
for (int i = 0; i < random; i++)
{
//a = obj1.fnSkipPatient(p);
string dummmy = "D";
int dum = 0;
//DateTime sdt = DateTime.Now;
cmdString = "INSERT INTO Patient_Data(PatientID,PatientName,F_H_G,F_H_GName,AgeOnRegn,Email,ContactNo,Gender,Married,AddressLine1,AddressLine2,City,PinCode,Religion,Occupation,RegTime,VisitDate,CurrDept,NextDept,PayID,PayDet1,PayDet2,PayDet3,PayValidity,Archived,UpdateUser,UpdateShift,UpdateDate,LocID,AddressLine3,Remark) VALUES (#PatientID,#PatientName,#F_H_G,#F_H_GName,#AgeOnRegn,#Email,#ContactNo,#Gender,#Married,#AddrLine1,#AddrLine2,#City,#PinCode,#Religion,#Occupation,#RegTime,#VisitDate,#CurrDept,#NextDept,#PayID,#PayDet1,#PayDet2,#PayDet3,#PayValidity,#Archived,#UpdateUser,#UpdateShift,#UpdateDate,#LocID,#AddrLine3,#Remark)";
con = new SqlConnection(str);
try
{
//log.Debug("Entering fnAddPatient method-Function to add a new patient into the database,generate registration bill");
con.Open();
transaction = con.BeginTransaction();
cmd = new SqlCommand(cmdString, con, transaction);
cmd.Parameters.Add("#PatientID", SqlDbType.VarChar, 12);
cmd.Parameters["#PatientID"].Value = p.HospitalNo;
cmd.Parameters.Add("#PatientName", SqlDbType.VarChar, 30);
cmd.Parameters["#PatientName"].Value = dummmy;
cmd.Parameters.Add("#F_H_G", SqlDbType.VarChar, 1);
cmd.Parameters["#F_H_G"].Value = dummmy;
cmd.Parameters.Add("#F_H_GName", SqlDbType.VarChar, 30);
cmd.Parameters["#F_H_GName"].Value = dummmy;
cmd.Parameters.Add("#AgeOnRegn", SqlDbType.Int);
cmd.Parameters["#AgeOnRegn"].Value = dum;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 40);
cmd.Parameters["#Email"].Value = dummmy;
cmd.Parameters.Add("#ContactNo", SqlDbType.VarChar, 12);
cmd.Parameters["#ContactNo"].Value = dummmy;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 1);
cmd.Parameters["#Gender"].Value = dummmy;
cmd.Parameters.Add("#Married", SqlDbType.VarChar, 1);
cmd.Parameters["#Married"].Value = dummmy;
cmd.Parameters.Add("#AddrLine1", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine1"].Value = dummmy;
cmd.Parameters.Add("#AddrLine2", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine2"].Value = dummmy;
cmd.Parameters.Add("#AddrLine3", SqlDbType.VarChar, 100);
cmd.Parameters["#AddrLine3"].Value = dummmy;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 20);
cmd.Parameters["#City"].Value = dummmy;
cmd.Parameters.Add("#PinCode", SqlDbType.Int);
cmd.Parameters["#PinCode"].Value = dum;
cmd.Parameters.Add("#Religion", SqlDbType.VarChar, 20);
cmd.Parameters["#Religion"].Value = dummmy;
cmd.Parameters.Add("#Occupation", SqlDbType.VarChar, 20);
cmd.Parameters["#Occupation"].Value = dummmy;
cmd.Parameters.Add("#RegTime", SqlDbType.DateTime);
cmd.Parameters["#RegTime"].Value = sdt;
cmd.Parameters.Add("#VisitDate", SqlDbType.DateTime);
cmd.Parameters["#VisitDate"].Value = sdt;
cmd.Parameters.Add("#CurrDept", SqlDbType.Int);
cmd.Parameters["#CurrDept"].Value = dum;
cmd.Parameters.Add("#NextDept", SqlDbType.Int);
cmd.Parameters["#NextDept"].Value = dum;
cmd.Parameters.Add("#PayId", SqlDbType.VarChar, 2);
cmd.Parameters["#PayId"].Value = dummmy;
cmd.Parameters.Add("#PayDet1", SqlDbType.VarChar, 15);
cmd.Parameters["#PayDet1"].Value = dummmy;
cmd.Parameters.Add("#PayDet2", SqlDbType.VarChar, 50);
cmd.Parameters["#PayDet2"].Value = dummmy;
cmd.Parameters.Add("#PayDet3", SqlDbType.VarChar, 15);
cmd.Parameters["#PayDet3"].Value = dummmy;
cmd.Parameters.Add("#PayValidity", SqlDbType.DateTime);
cmd.Parameters["#PayValidity"].Value = sdt;
cmd.Parameters.Add("#Archived", SqlDbType.VarChar, 1);
cmd.Parameters["#Archived"].Value = dummmy;
cmd.Parameters.Add("#UpdateUser", SqlDbType.VarChar, 20);
cmd.Parameters["#UpdateUser"].Value = dummmy;
cmd.Parameters.Add("#UpdateShift", SqlDbType.Int);
cmd.Parameters["#UpdateShift"].Value = dum;
cmd.Parameters.Add("#UpdateDate", SqlDbType.DateTime);
cmd.Parameters["#UpdateDate"].Value = sdt;
cmd.Parameters.Add("#PatientCount", SqlDbType.Int);
cmd.Parameters["#PatientCount"].Value = dum;
cmd.Parameters.Add("#LocId", SqlDbType.VarChar, 2);
cmd.Parameters["#LocId"].Value = dummmy;
cmd.Parameters.Add("#Remark", SqlDbType.VarChar, 100);
cmd.Parameters["#Remark"].Value = dummmy;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
string result = cmd.ExecuteNonQuery().ToString();
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
}
}
}
Move cmd.Parameters.Clear(); after cmd.ExecuteNonQuery()
Try with cmd.ExecuteNonQuery() only.
Also note that if your isValidInt is false, your query will not be executed.. So, first check whether your isValidInt is true. Better you change your logic
You must commit changes in transaction and also cosider transaction.Rollback(); in the catch
I think you are missing transaction.Commit(); after cmd.ExecuteNonQuery();.
try
{
con.Open();
transaction = con.BeginTransaction();
cmd = new SqlCommand(cmdString, con, transaction);
cmd.Parameters.AddWithValue("#PatientID", p.HospitalNo);
// Continue your usual work
cmd.Parameters.AddWithValue("#Remark", dummmy);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
transaction.Commit();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
transaction.Rollback();
}
finally
{
con.Close();
}
Something similar to above code should work for you.
Hope it helps.
execute the following code in server management studio....
GRANT INSERT ON [dbo].[Patient_Data] TO public
hope it works...
1)Make Sure that the connection string is valid.
2)If you close and open the sql server management studio the database will be switched over to "master", you have to change the control to your DB.You can see a dropdownbox in the sql editor tool bar where you can select the DB that where the current query should executed.
I am working on exporting CSV to SQL server but it doesn't export anything. I have following code:
protected void uploadButton_Click(object sender, EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("IP");
tblReadCSV.Columns.Add("activityStart");
tblReadCSV.Columns.Add("activityEnd");
tblReadCSV.Columns.Add("RCPTcommands");
tblReadCSV.Columns.Add("DataCommands");
tblReadCSV.Columns.Add("MessageRecipients");
tblReadCSV.Columns.Add("FilterResultColor");
tblReadCSV.Columns.Add("complaintRate");
tblReadCSV.Columns.Add("trapStart");
tblReadCSV.Columns.Add("trapEnd");
tblReadCSV.Columns.Add("trapHits");
tblReadCSV.Columns.Add("sampleHelo");
tblReadCSV.Columns.Add("sampleMailFrom");
tblReadCSV.Columns.Add("comments");
tblReadCSV.Columns.Add("URL");
string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadFiles/" + path));
path = Server.MapPath("~/UploadFiles/" + path);
TextFieldParser csvParser = new TextFieldParser(path);
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true))
{
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
string strCon = ConfigurationManager.ConnectionStrings["conMailMonitor"].ConnectionString;
string strSql = "INSERT INTO tblSnds(IP,activityStart,activityEnd,RCPTcommands,DataCommands,MessageRecipients,FilterResultColor,complaintRate,trapStart,trapEnd,trapHits,sampleHelo,sampleMailFrom,comments,URL)VALUES(#IP,#activityStart,#activityEnd,#RCPTcommands,#DataCommands,#MessageRecipients,#FilterResultColor,#complaintRate,#trapStart,#trapEnd,#trapHits,#sampleHelo,#sampleMailFrom,#comments,#URL)";
SqlConnection con = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#IP", SqlDbType.VarChar, 50, "IP");
cmd.Parameters.Add("#activityStart", SqlDbType.VarChar, 50, "activityStart");
cmd.Parameters.Add("#activityEnd", SqlDbType.VarChar, 50, "activityEnd");
cmd.Parameters.Add("#RCPTcommands", SqlDbType.VarChar, 50, "RCPTcommands");
cmd.Parameters.Add("#DataCommands", SqlDbType.VarChar, 50, "DataCommands");
cmd.Parameters.Add("#MessageRecipients", SqlDbType.VarChar, 50, "MessageRecipients");
cmd.Parameters.Add("#FilterResultColor", SqlDbType.VarChar, 50, "FilterResultColor");
cmd.Parameters.Add("#complaintRate", SqlDbType.VarChar, 50, "complaintRate");
cmd.Parameters.Add("#trapStart", SqlDbType.VarChar, 50, "trapStart");
cmd.Parameters.Add("#trapEnd", SqlDbType.VarChar, 50, "trapEnd");
cmd.Parameters.Add("#trapHits", SqlDbType.VarChar, 50, "trapHits");
cmd.Parameters.Add("#sampleHelo", SqlDbType.VarChar, 50, "activityEnd");
cmd.Parameters.Add("#sampleMailFrom", SqlDbType.VarChar, 50, "sampleMailFrom");
cmd.Parameters.Add("#comments", SqlDbType.VarChar, 50, "comments");
cmd.Parameters.Add("#URL", SqlDbType.VarChar, 50, "URL");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
Label1.Text = "File successfully uploaded";
}
Contents of CSV are:
216.211.128.7,8/12/2013 8:00 AM,8/13/2013 8:00 AM,6610,5642,5644,GREEN,< 0.1%,8/12/2013 11:23 AM,8/12/2013 11:36 AM,4,mail2.adhost.com,bpsupport#betterphoto.com,
When I debug, I see that control doesnt go inside the while loop
while (!(csvParser.EndOfData == true))
Please suggest how to do it ?
You have to use MyReader.ReadFields() to advance the reader to the next line:
// csvParser.ReadLine(); <-- remove this
while (!csvParser.EndOfData) {
string[] fields = csvParser.ReadFields();
tblReadCSV.Rows.Add(fields);
}
MSDN:
Reads all fields on the current line, returns them as an array of
strings, and advances the cursor to the next line containing data.
The problem was that you are using ReadLine first which skips the first line.
I do not clearly understand how to format the SqlDataAdapter for output variables when working with C#
Error Message:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Code Example (Stored Procedure works fine):
private DataTable updateOrdEodHold(DataTable tb, out string mnpft,
out string authld, out string trd, out string hld, out string extnow)
{
// Start the connection string.
string connstr = ConfigurationManager.ConnectionStrings
["LocalSqlServer"].ConnectionString;
SqlConnection myConn = new SqlConnection(connstr);
// Declare symbol and assign for Errors Catch Exception.
string Symbol = "";
string sqlComm = "dbo.UpdateOrdEodHold";
DataTable HoldVals = new DataTable();
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlComm, myConn);
dataAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
string ticker = (string)Convert.ToString(tb.Rows[0]["Ticker"]);
// update Symbol for Catch ex
Symbol = ticker.ToString();
String company = (string)Convert.ToString(tb.Rows[0]["Company"]);
String avgprofit = (string)Convert.ToString(tb.Rows[0]["AvgProfit"]);
String extdte = (string)Convert.ToString(tb.Rows[0]["ExitDate"]);
dataAdp.SelectCommand.Parameters.Clear();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#ticker",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#ticker"].Value =
(string)ticker.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#company",
SqlDbType.VarChar, 25));
dataAdp.SelectCommand.Parameters["#company"].Value =
(string)company.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#avgpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#avgpft"].Value =
(string)avgprofit.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#mnpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#mnpft"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#authld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#authld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#hld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#hld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#trd",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#trd"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extnow",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#extnow"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extdte",
SqlDbType.VarChar, 15));
dataAdp.SelectCommand.Parameters["#extdte"].Value =
(string)extdte.ToString();
dataAdp.Fill(HoldVals);
mnpft = HoldVals.Rows[0]["MinProfit"].ToString();
authld = HoldVals.Rows[0]["AutoHold"].ToString();
trd = HoldVals.Rows[0]["Trade"].ToString();
hld = HoldVals.Rows[0]["Hold"].ToString();
extnow = HoldVals.Rows[0]["ExitNow"].ToString();
return HoldVals;
}
You need to hold a reference to the Output parameter variable so that you can access the value returned to it using parameter.Value once the adapter has executed the command.
//Create the parameter
SqlParameter parameter = new SqlParameter("#mnpft", SqlDbType.VarChar);
//Set the parameter direction as output
parameter.Direction = ParameterDirection.Output;
sqlCommand.Parameters.Add(parameter);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dataSet);
//Fetch the output parameter after doing the Fill
string outputValue = Convert.ToString(parameter.Value);