System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#SSN" - c#

I am developing a Windows Forms application in C#. I have always encryption columns in SQL Server.
My goal is to pull data from the datagridview in the form and display data.
I want to pull the data with the where operator and display it in the datagridview, but I am getting the following error.
Is there any way to do this?
I would be glad if you help!!
Error
System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#SSN".
Code:
private void btnSearch_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source = " + IP + "; Initial Catalog = " + db + "; Persist Security Info = False; User ID = " + username + "; Password = " + password + ";Column Encryption Setting = Enabled;");
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE TEST_TYPE = #SSN";
SqlParameter paramSSN = cmd.CreateParameter();
paramSSN.ParameterName = #"#SSN";
//paramSSN.ParameterName = "#SSN";
paramSSN.DbType = DbType.AnsiStringFixedLength;
paramSSN.Direction = ParameterDirection.Input;
paramSSN.Value = "'INITIAL_TEST'";
paramSSN.Size = 18;
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}
}

When I changed my code like this, the error went away.I found the solution.
ConnectionString();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE "+comboBox1.Text+" =
#SSN";
SqlParameter paramSSN = cmd.CreateParameter();
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
dataAdapter.SelectCommand.Parameters.Add("#SSN",
SqlDbType.VarChar,18).Value = textBox2.Text;
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}

Related

C# UPDATE directly after INSERT but getting EXTRA INSERT

I've got the following code:
private void btnAddMatter_Click(object sender, EventArgs e)
{
MatterCode = "";
EntityID = 0;
FeeEarnerID = 0;
OpenedByUserID = 0;
CompanyContactDetailsID = 0;
Description = "";
OurReference = "";
TheirReference = "";
DateOpened = DateTime.Now;
MatterTypeID = 0;
DepartmentID = 0;
ResponsibleUserID = 0;
TrustBankAccountID = 0;
BusinessBankAccountID = 0;
string connectionString = "Data Source=***\\SQLEXPRESS;Initial Catalog=STUPELG;Persist Security Info=True;User ID=***;Password=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Matter ( MatterCode, EntityID, FeeEarnerID, OpenedByUserID, CompanyContactDetailsID, Description," +
" OurReference, TheirReference, DateOpened, MatterTypeID, DepartmentID, ResponsibleUserID, TrustBankAccountID, BusinessBankAccountID)" +
" VALUES ( #MatterCode, #EntityID, #FeeEarnerID, #OpenedByUserID, #CompanyContactDetailsID, #Description," +
" #OurReference, #TheirReference, #DateOpened, #MatterTypeID, #DepartmentID, #ResponsibleUserID, #TrustBankAccountID, #BusinessBankAccountID);" +
" SELECT SCOPE_IDENTITY();");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterID", MatterID);
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
cmd.Parameters.AddWithValue("#EntityID", EntityID);
cmd.Parameters.AddWithValue("#FeeEarnerID", FeeEarnerID);
cmd.Parameters.AddWithValue("#OpenedByUserID", OpenedByUserID);
cmd.Parameters.AddWithValue("#CompanyContactDetailsID", CompanyContactDetailsID);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#OurReference", OurReference);
cmd.Parameters.AddWithValue("#TheirReference", TheirReference);
cmd.Parameters.AddWithValue("#MatterTypeID", MatterTypeID);
cmd.Parameters.AddWithValue("#DepartmentID", DepartmentID);
cmd.Parameters.AddWithValue("#ResponsibleUserID", ResponsibleUserID);
cmd.Parameters.AddWithValue("#TrustBankAccountID", TrustBankAccountID);
cmd.Parameters.AddWithValue("#BusinessBankAccountID", BusinessBankAccountID);
cmd.Parameters.AddWithValue("#DateOpened", DateOpened);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UPDATE Matter SET MatterCode = #MatterCode WHERE MatterID = " + MatterCode);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
connection.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Matter " + MatterCode + " successfully created");
}
After the row is inserted, the new MatterID (primary key that is generated automatically) should be copied to the MatterCode field. Currently it works EXCEPT that there is an extra row that is generated at when the button is clicked:
How do I fix this???
Well - this is because your code is executing the INSERT query twice......
connection.Open();
cmd.ExecuteNonQuery(); // first execution
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID); // second execution
I'm not entirely sure what you wanted to do with that SqlDataAdapter - but it's using the same SqlCommand from before, with the INSERT statement, which gets executed a second time......
You can replace this:
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
with
MatterCode = cmd.ExecuteScalar().ToString();
as ExecuteScalar runs the command and returns the value of the first column of the first row of the first resultset.

Why the database verification code can not be executed in c#

This is an existing class in the dll to verify that the database exists
public class CheckDataBaseExists
{
public void CheckDataBase(string Server, string Database_name)
{
SqlConnection con = new SqlConnection(#"Data Source=" + Server + ";Initial Catalog=master;Integrated Security=True");
con.Open();
con.InfoMessage += connection_InfoMessage;
SqlCommand comm = new SqlCommand(#"if DB_ID('" + Database_name + "') is null print '" + Database_name + " is not exist !\r\nCreate new database ?'", con);
SqlDataAdapter adp = new SqlDataAdapter(comm);
DataTable set = new DataTable();
adp.Fill(set);
con.Close();
}
public static void connection_InfoMessage( object sender, SqlInfoMessageEventArgs e)
{
if( MessageBox.Show(e.Message, e.Source, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
{
try
{
The form of entering the name of the server and the database if the database did not exist
#region create form
Label creating = new Label();
creating = new System.Windows.Forms.Label();
creating.SuspendLayout();
//
// creating
//
creating.AutoSize = true;
creating.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
creating.Font = new System.Drawing.Font("Tahoma", 12F);
creating.Location = new System.Drawing.Point(25, 3);
creating.Name = "creating";
creating.Size = new System.Drawing.Size(150, 19);
creating.TabIndex = 0;
creating.Text = "Creating database...";
Form create_db = new Form();
create_db.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
create_db.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
create_db.BackColor = System.Drawing.Color.White;
create_db.ClientSize = new System.Drawing.Size(200, 25);
create_db.ControlBox = false;
create_db.TopMost = true;
create_db.Controls.Add(creating);
create_db.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
create_db.MaximizeBox = false;
create_db.MinimizeBox = false;
create_db.Name = "Create";
create_db.ShowIcon = false;
create_db.ShowInTaskbar = false;
create_db.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
create_db.Text = "Creating Databse...";
create_db.ResumeLayout(false);
create_db.PerformLayout();
create_db.Controls.Add(creating);
create_db.ShowDialog();
#endregion
Read the file that contains the database name and the server
string[] read_file = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + #"\" + "ConReq.HP");
string db_src = read_file[2],
db_nm = read_file[0].Substring(7, read_file[0].Length - 7),
db_server = read_file[1].Substring(7, read_file[1].Length - 7),
location = read_file[3];
The SQL file contains commands to create the database with the name of the database to be created
string read_DBsql = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + #"\Required\DB\DB.sql");
read_DBsql = read_DBsql.Replace("DataBaseName", db_nm);
Create a connection and execute the command
SqlConnection con = new SqlConnection("Data Source=" + db_server + ";Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True");
con.Open();
SqlCommand comm = con.CreateCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = read_DBsql;
comm.ExecuteNonQuery();
con.Close();
}
catch (Exception db_e)
{
MessageBox.Show(db_e.Message, db_e.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
But what happens is that when a message appears make sure there is no database and question is do you want to create one.
when I want to create a new one, appears the Form created then nothing happens and remains visible. As in the pictures
Why you are using Info_Message event for such simplest thing ( checking database)
Just check the result is below query:
String query = "select count(*) from sys.databases where name = 'dbname'"
Execute above query as:
var count = cmd.ExecuteScalar();
Also can you please show full code written in Info_Message

Opening connections to multiple databases

I want to connect to multiple databases and want to run some query on through those connections, but it's not working.
string source = "10.0.0.0";
string user = "abc";
string password="abc";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
string source = dt.Rows[i][2].ToString();
string user = dt.Rows[i][1].ToString();
int password = Convert.ToInt32(user) + 111;
OracleConnection conn = new OracleConnection("Data Source = " + source + ": 1521/rms; User id = " + user + "; Password=" + password + ";");
conn.Open();
OracleCommand cmd = new OracleCommand(" SELECT SUM(AI_TRN) FROM tr_rtl where DC_DY_BSN = '06-04-2016'and mall like '%" + Mallname.Text + "%' ", conn);
cmd.ExecuteNonQuery();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
oda.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
label1.Text = source;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
sorry i have posted the wrong code
What you probably will need to do is iterate through a list of connections and populate one data table with all the results. Here is an example:
List<OracleConnections> Connections = new List<OracleConnections>();
DataTable FinalResults = new DataTable();
foreach (var Connection in Connections)
{
using (Connection)
{
DataTable TemporaryTable = new DataTable();
Connection.Open();
OracleCommand Command = new OracleCommand("SomeCommandText", Connection);
OracleDataAdapter Adapter = new OracleDataAdapter(Command);
Adapter.Fill(TemporaryTable);
FinalResults.Merge(TemporaryTable);
}
}
This should give you all the results of each database/connection in one final table (Results) or you can do a dataset if it is different columns/data within each connection.
Updated to explain comments listed above.
string Source = "10.0.0.0";
string User = "abc";
string Password = "abc";
DataTable dt = new DataTable();
// Remove this or use another reference (different table), you just created the table ^, it has no rows. -> "for (int i = 0; i < dt.Rows.Count; i++)"

Using ExecuteReader instead of SQLDataAdapter

I've got a C# project where I'm trying to export the results of a datagrid. Sometimes the data gets quite large, so rather than re-executing the code I want to dump the dataset into a session variable.
This works perfectly in most of my projects. One example from a project where I use this is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
//Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");
//string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
//string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
//sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
//sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(DISTINCT Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
sqlquery = sqlquery + "from (SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM ClosedClaims_MERGE ";
sqlquery = sqlquery + "UNION SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM tblAuditing) CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "WHERE CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "' ";
sqlquery = sqlquery + "GROUP BY Spare, PROC_NM, AdminLevel ";
sqlquery = sqlquery + "ORDER BY Count(Claim_ID) DESC";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "dsEffVol");
// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSEffVol"] = ds;
// Perform the binding.
grdEffVol.Attributes.Add("style", "overflow:auto");
//GridView_WODetails.Attributes.Add("style", "table-layout:fixed");
grdEffVol.AutoGenerateColumns = true;
grdEffVol.DataSource = ds;
grdEffVol.DataBind();
}
I've got a new project where I'm not using SQL strings, but instead I'm pulling data based on SQL Server Stored Procedures. The code block there is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from RM_tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
string MyUseDates = DT1[4].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;
//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}
else
{
}
try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
GridView_Reports.DataBind();
// Add this to a session variable so the datagrid won't get NULLed out on repost
GridView_Reports.DataBound += GridView_Reports_RowDataBound;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
Console.WriteLine(ex);
return;
}
finally
{
connection2.Close();
connection2.Dispose();
}
}
}
}
}
}
I'm kind of guessing my way through this, and I'm not sure if I'm reading the data into a dataset properly. The page is shutting down, and I'm pretty sure the problem is in the lines:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Quite honestly, I've googled SqlDataReader vs SqlDataAdapter and can't really find anything, but I need to fill the session variable in the second example and also have the datagrid populate properly. So, in essence, I need to put the results of a Stored Procedure into a dataset. Can anyone offer suggestions on what I'm doing wrong?
I'm pretty sure most controls don't accept readers in their DataSource property. Plus the majority of readers are forward-only, so although you're trying to store the reader as a session variable, chances are you would only be able to read it once.
Why do you want to use a reader for this when your post seems to indicate that you know you need to use a DataSet? Why not just use an adapter the way you show in your first post? Adapters work fine with commands that use sprocs.
Instead of:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Just use:
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");
Session["SSRptMenu"] = ds;
GridView_Reports.DataSource = ds;

C# How can i update some column datetime in datagridview to database

i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.

Categories

Resources