I'm using a stored procedure to update the rows in the column where the consignment number = #consignmentnumber.
Here is a screen of the code.
I think I'm missing something but I can't work out I'm actually missing, can anyone help?
protected void BtnReceived_Click(object sender, EventArgs e)
{
IncrementStatusOfConsignment(sender);
}
private static void IncrementStatusOfConsignment(object sender)
{
var button = (Button) sender;
var gridviewrow = (GridViewRow) button.Parent.Parent;
var consignmentnumber = gridviewrow.Cells[3].Text;
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
con.Open();
using (var cmd = new SqlCommand("Test", con))
{
cmd.CommandType = CommandType.StoredProcedure;
var sqlparam = cmd.Parameters.Add("#consignmentnumber", SqlDbType.VarChar);
sqlparam.Value = consignmentnumber;
cmd.ExecuteNonQuery();
}
}
}
Can anyone tell me where I've gone wrong or what I'm missing?
I constantly get this error:
If I set the param to Int it still doesn't work.
If you have declared column consignmentnumber as Numeric(18, 0) then
var sqlparam = cmd.Parameters.Add("#consignmentnumber", SqlDbType.Decimal);
sqlparam.Value = consignmentnumber;
OR something like that:
var sqlparam = cmd.Parameters.Add("#consignmentnumber", SqlDbType.NVarChar, 18);
sqlparam.Value = consignmentnumber;
Related
I have 2 tables. Main_items and Help_items.
Main_items has these columns
(main_items_id,main_items_name)
Help_items has these columns
(help_items_id,Help_items_name, main_items_id).
I wrote this Procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `thamer1`(in main_items_id_ int,
out res int)
BEGIN
declare a int;
declare b int;
select count(help_items_id)
into a from help_items
where main_items_id=main_items_id_;
if a=0 then
set b=(main_items_id_*10)+1;
set res=b;
else
select COALESCE(max(help_items_id),0)+1
into res
from help_items
where main_items_id=main_items_id_;
end if;
END
This procedure works with MySql WrokBench.
And this for c# code
private void a_KeyDown(object sender, KeyEventArgs e)
{
using (MySqlConnection mysqlcon6 = new
MySqlConnection(connectString))
{
mysqlcon6.Open();
MySqlCommand mysqlcmd6 = new MySqlCommand("thamer1", mysqlcon6);
mysqlcmd6.CommandType = CommandType.StoredProcedure;
mysqlcmd6.CommandText = "thamer1";
mysqlcmd6.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value=HITEM.Text;
mysqlcmd6.ExecuteNonQuery();
// MessageBox.Show("saved");
// GridFill();
}
}
I select value (for main_items_id) from DataGrideView and fetch it into textbox named a.
When I press ENTER I get this Message
System.FormatException:' Input string was not in a correct format'
I hope to help me to solve this error.
Remove the portion of this line that sets the parameter value:
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value=HITEM.Text;
It looks like you expect that to bind the result of #res to the HITEM textbox, and that's not what happens. HITEM.Text is just a string, and when you assign that value to an int parameter, you're telling MySql you expect it to be able to parse that string into an int.
Instead, only create the parameter, like this:
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32);
You also need to tell ADO.Net this is an OUTPUT parameter. Then check the parameter value after the query runs by assigning the parameter value to HITEM.Text rather than from HITEM.Text:
private void a_KeyDown(object sender, KeyEventArgs e)
{
//You can re-use the *names* of these variables, since their scopes are limited to the method
//You can also stack them to share the same scope block and reduce nesting/indentation
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
// mysqlcmd6.CommandText = "thamer1"; //you already did this in constructor. Don't need to do it again
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
//DON'T assign to the Value, but DO make sure ADO.Net understands this is an OUTPUT parameter
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
//wait as long as possible to call Open()
con.Open();
cmd.ExecuteNonQuery();
//Now you can assign **to** HITEM.Text, rather than from it.
HITEM.Text = cmd.Parameters["#res"].Value;
}
//End the scope as soon as possible, so the connection can be disposed faster
// MessageBox.Show("saved");
// GridFill();
}
And here it is again without all the extra comments:
private void a_KeyDown(object sender, KeyEventArgs e)
{
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = a.Text;
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
HITEM.Text = cmd.Parameters["#res"].Value;
}
}
Even better practice would move all your SQL methods to a separate class, away from your event handlers. The event handlers should only need to call methods in the new class, like this:
public static class DB
{
private static string connectionString = "...";
public static int thamer(int main_item_id)
{
using (var con = new MySqlConnection(connectString))
using (var cmd = new MySqlCommand("thamer1", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = main_item_id;
cmd.Parameters.Add("#res", MySqlDbType.Int32).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
return (int)cmd.Parameters["#res"].Value;
}
}
}
private void a_KeyDown(object sender, KeyEventArgs e)
{
HITEM.Text = DB.thamer(int.Parse(a.Text)).ToString();
}
Change this
mysqlcmd6.Parameters.Add("#main_items_id_",
MySqlDbType.Int32).Value = a.Text;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value =
HITEM.Text;
to
int value1 = 0;
int value2 = 0;
if (!Int32.Text.TryParse(a.Text) || !Int32.TryParse(HITEM.Text))
{
return;
}
mysqlcmd6.Parameters.Add("#main_items_id_", MySqlDbType.Int32).Value = value1;
mysqlcmd6.Parameters.Add("#res", MySqlDbType.Int32).Value = value2;
I need help on determining what cause the error of my code.
"Conversion failed when converting the varchar value 'Undergraduate' to data type int." when i hit the ADD Button.
I'm struggling to find what went wrong. It worked at first but suddenly, the error alway occur.
This is the full code;
private void btnadd_Click(object sender, EventArgs e)
{
using (SqlConnection conncurr = new SqlConnection(Properties.Settings.Default.connectionstring))
using (SqlCommand cmdcurr = new SqlCommand("curriculumadd", conncurr))
{
try
{
conncurr.Open();
var newaccountparam1 = new SqlParameter("#dccode", SqlDbType.VarChar);
var newaccountparam2 = new SqlParameter("#dcdesc", SqlDbType.VarChar);
var newaccountparam3 = new SqlParameter("#currtitle", SqlDbType.VarChar);
var newaccountparam4 = new SqlParameter("#units", SqlDbType.Int);
var newaccountparam5 = new SqlParameter("#labunits", SqlDbType.Int);
var newaccountparam6 = new SqlParameter("#lecunits", SqlDbType.Int);
var newaccountparam7 = new SqlParameter("#yearlevel", SqlDbType.Int);
var newaccountparam8 = new SqlParameter("#sem", SqlDbType.Int);
var newaccountparam9 = new SqlParameter("#labhrs", SqlDbType.Int);
var newaccountparam10 = new SqlParameter("#lechrs", SqlDbType.Int);
var newaccountparam11 = new SqlParameter("#acadlevel", SqlDbType.Int);
var newaccountparam12 = new SqlParameter("#subjcode", SqlDbType.VarChar);
var newaccountparam13 = new SqlParameter("#subjdesc", SqlDbType.VarChar);
var newaccountparam14 = new SqlParameter("#subjcat", SqlDbType.VarChar);
var newaccountparam15 = new SqlParameter("#curreffectvty", SqlDbType.VarChar);
newaccountparam1.Value = txtcoursecode.Text;
newaccountparam2.Value = txtdcourse.Text;
newaccountparam3.Value = currtitle;
newaccountparam4.Value = totalunits;
newaccountparam5.Value = txtlabunits.Text;
newaccountparam6.Value = txtlecunits.Text;
newaccountparam7.Value = yearlevel;
newaccountparam8.Value = semestr;
newaccountparam9.Value = labhrs;
newaccountparam10.Value = lecthrs;
newaccountparam11.Value = acadlevel;
newaccountparam12.Value = txtsubjcode.Text;
newaccountparam13.Value = txtdesctitle.Text;
newaccountparam14.Value = cmbsubjfield.Text;
newaccountparam15.Value = txteffectivity.Text;
cmdcurr.Parameters.Add(newaccountparam1);
cmdcurr.Parameters.Add(newaccountparam2);
cmdcurr.Parameters.Add(newaccountparam3);
cmdcurr.Parameters.Add(newaccountparam4);
cmdcurr.Parameters.Add(newaccountparam5);
cmdcurr.Parameters.Add(newaccountparam6);
cmdcurr.Parameters.Add(newaccountparam7);
cmdcurr.Parameters.Add(newaccountparam8);
cmdcurr.Parameters.Add(newaccountparam9);
cmdcurr.Parameters.Add(newaccountparam10);
cmdcurr.Parameters.Add(newaccountparam11);
cmdcurr.Parameters.Add(newaccountparam12);
cmdcurr.Parameters.Add(newaccountparam13);
cmdcurr.Parameters.Add(newaccountparam14);
cmdcurr.Parameters.Add(newaccountparam15);
cmdcurr.CommandType = CommandType.StoredProcedure;
cmdcurr.ExecuteNonQuery();
}
finally
{
conncurr.Close();
conncurr.Dispose();
userlogsmonitor.ActiveForm.Refresh();
}
}
}
Code for converting string to integer;
private void cmbacadlevel_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmbacadlevel.SelectedItem.ToString().Trim())
{
case "Undergraduate":
acadlevel = 1;
break;
case "Masteral":
acadlevel = 2;
break;
case "Doctorate":
acadlevel = 3;
break;
case "Senior High School":
acadlevel = 4;
break;
}
I tried editing the code but it seems not lucky enough. Can you please scrutinize my code and try to give an idea on how to deal with it?
Verify following things
Order and type of parameter is same as in the stored procedure
Either use breakpoint to verify values of int parameters
Or use SQL Server Profiler to to check if int parameters have valid values.
The first item of the Dropbox is not working when the page loaded but if select the second item in the Dropbox the form will populate with the relevant data. If I come back to first item selected previously it will work this time. Any help please. Thanks
HTML code
<asp:DropDownList ID="DropDownListUpdateSample" runat="server" Height="37px" Width="132px" CssClass="auto-style111" AutoPostBack = "true" OnSelectedIndexChanged="DropDownListUpdateSample_SelectedIndexChanged" AppendDataBoundItems="False">
C# Code
//Code to populate the Dropbox
using (SqlCommand cmd5 = new SqlCommand(#"SELECT Patient.MBID, Sample.SampleID
FROM Patient INNER JOIN
Sample ON Patient.MBID = Sample.MBID
WHERE
Patient.Surname = #Surname and Patient.DOB = convert(datetime, #DOB, 103)
ORDER by Sample.SampleID ASC ", con))
{
cmd5.Parameters.AddWithValue("#Surname", txtSearchSurname.Text);
cmd5.Parameters.AddWithValue("#DOB", txtSearchDOB.Text);
SqlDataAdapter da5 = new SqlDataAdapter(cmd5);
DataSet dt5 = new DataSet();
da5.Fill(dt5, "Sample");
DataTable myDataTable = dt5.Tables[0];
// Loop to insert the Sample ID in the Drop box
foreach (DataRow tempRow_Variable in myDataTable.Rows)
{
var tempRow = tempRow_Variable;
DropDownListUpdateSample.Items.Add(tempRow["SampleID"].ToString());
}
}
//Code to Populate the form after an item is selected from the Dropbox
protected void DropDownListUpdateSample_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand st = new SqlCommand(#"SELECT *
FROM Sample
WHERE
SampleID=#SampleID", con))
{
st.Parameters.AddWithValue("#SampleID", DropDownListUpdateSample.SelectedItem.Value);
using (SqlDataReader reader = st.ExecuteReader())
{
while (reader.Read())
{
txtUpdateSampleID.Text = reader["SampleID"].ToString();
txtUpdateSampleType.Text = reader["SampleType"].ToString();
txtUpdateSampleDate.Text = reader["SampleDate"].ToString();
txtUpdateSampleTrial.Text = reader["SampleTrial"].ToString();
DropDownListUpdateFirstSample.SelectedItem.Value = reader["FirstSample"].ToString();
txtUpdateSampleComments.Text = reader["Comments"].ToString();
txtUpdateSampleConsultant.Text = reader["ConsultantName"].ToString();
DropDownListUpdate.SelectedItem.Value = reader["Diagnosis"].ToString();
DropDownListUpdateConsentConfirm.SelectedItem.Value = reader["ConsentConfirmed"].ToString();
txtUpdateConsentDate.Text = reader["DateConsent"].ToString();
txtUpdateOrther.Text = reader["OtherConsent"].ToString();
DropDownListUpdateSectionDecline.SelectedItem.Value = reader["SectionDecline"].ToString();
DropDownListUpdateQuarantine.SelectedItem.Value = reader["Quarantine"].ToString();
DropDownListUpdateClinicalArchive.SelectedItem.Value = reader["ClinicalArchive"].ToString();
DropDownListUpdateResearch.SelectedItem.Value = reader["Research"].ToString();
//DropDownListUpdateClinicalArchive.SelectedItem.Value= reader["Research"].ToString();
}
}
}
con.Close();
}
}
Use the below code:
public void functionForSelectedValue(int id)
{
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand st = new SqlCommand(#"SELECT *
FROM Sample
WHERE
SampleID=#SampleID", con))
{
st.Parameters.AddWithValue("#SampleID", id);
using (SqlDataReader reader = st.ExecuteReader())
{
while (reader.Read())
{
txtUpdateSampleID.Text = reader["SampleID"].ToString();
txtUpdateSampleType.Text = reader["SampleType"].ToString();
txtUpdateSampleDate.Text = reader["SampleDate"].ToString();
txtUpdateSampleTrial.Text = reader["SampleTrial"].ToString();
DropDownListUpdateFirstSample.SelectedItem.Value = reader["FirstSample"].ToString();
txtUpdateSampleComments.Text = reader["Comments"].ToString();
txtUpdateSampleConsultant.Text = reader["ConsultantName"].ToString();
DropDownListUpdate.SelectedItem.Value = reader["Diagnosis"].ToString();
DropDownListUpdateConsentConfirm.SelectedItem.Value = reader["ConsentConfirmed"].ToString();
txtUpdateConsentDate.Text = reader["DateConsent"].ToString();
txtUpdateOrther.Text = reader["OtherConsent"].ToString();
DropDownListUpdateSectionDecline.SelectedItem.Value = reader["SectionDecline"].ToString();
DropDownListUpdateQuarantine.SelectedItem.Value = reader["Quarantine"].ToString();
DropDownListUpdateClinicalArchive.SelectedItem.Value = reader["ClinicalArchive"].ToString();
DropDownListUpdateResearch.SelectedItem.Value = reader["Research"].ToString();
//DropDownListUpdateClinicalArchive.SelectedItem.Value= reader["Research"].ToString();
}
}
}
con.Close();
}
}
protected void DropDownListUpdateSample_SelectedIndexChanged(object sender, EventArgs e)
{
functionForSelectedValue(DropDownListUpdateSample.SelectedItem.Value);
}
And in page load:
call
foreach (DataRow tempRow_Variable in myDataTable.Rows)
{
var tempRow = tempRow_Variable;
DropDownListUpdateSample.Items.Add(tempRow["SampleID"].ToString());
}
DropDownListUpdateSample.Items.FindByValue("IdforWhichYouWantTobindIt").Selected = true;
functionForSelectedValue(DropDownListUpdateSample.SelectedItem.Value);
Hope this solves your problem.
My problem is that when it gets updated it adds the previous data which was in it Again and again
and i use a telerik grid view
here my code in 3 layers
first one
private void btnSbmt_Click(object sender, EventArgs e)
{
foreach (var row in radGridView1.Rows)
{
_MyName.Add((string)row.Cells[1].Value);
}
foreach (var row in radGridView1.Rows)
{ // 0 - first column
_MyAmount.Add((int)row.Cells[2].Value);
}
foreach (var row in radGridView1.Rows)
{
_MyPrice.Add((decimal)row.Cells[3].Value);
}
Ref_View_Model = new View_model._View_Model();
Ref_View_Model.GetInsertProduct(_myName, _myAmount, _myPrice, txtDt.Text);
radGridView1.CurrentRow.Delete();
productTableAdapter.Update(sales_and_Inventory_SystemDataSet);
productTableAdapter.Fill(sales_and_Inventory_SystemDataSet.Product);
MessageBox.Show("Product(s) were added", "Done", MessageBoxButtons.OK);}
second one
public void GetInsertProduct( List<string> _name, List<int> _amount, List<decimal> _price, string _date)
{
Ref_Model = new Model._Model();
Ref_Model.InsertProduct( _name, _amount, _price, _date);
}
and the Third one
public void InsertProduct(List<string> _myName,
List<int> _myAmount,
List<decimal> _myPrice, string _date)
{
Connection_String = myconnection string
Query = #"INSERT INTO dbo.product(Name, Amount, Price, [date])
VALUES(#Name, #Amount, #Price, #Date);";
using ( Con = new SqlConnection(Connection_String))
using ( Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#Name", SqlDbType.NVarChar);
Cmd.Parameters.Add("#Amount", SqlDbType.Int);
Cmd.Parameters.Add("#Price", SqlDbType.Decimal);
// Cmd.Parameters.Add("#Date", SqlDbType.NVarChar);
Cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Convert.ToDateTime(_date);
Cmd.Connection = Con;
Con.Open();
int recordsToAdd = _myName.Count();
for(int x = 0; x < recordsToAdd; x++)
{
Cmd.Parameters["#Name"].Value = _myName[x];
Cmd.Parameters["#Amount"].Value = _myAmount[x];
Cmd.Parameters["#Price"].Value = _myPrice[x];
Cmd.Parameters["#Date"].Value = _date;
Cmd.ExecuteNonQuery();
}
}
}
It seems that you are using global variables to keep the values that you read from the grid. If you don't clear them after the first insert, you have still the values in the global lists and you add them again to the datatable
Of course you can use just one loop to reload the global variables with the actual values present in the grid
private void btnSbmt_Click(object sender, EventArgs e)
{
// This removes whatever is in the lists
_MyName.Clear();
_MyAmount.Clear();
_MyPrice.Clear();
// and now start adding items from scratch
foreach (var row in radGridView1.Rows)
{
_MyName.Add((string)row.Cells[1].Value);
_MyAmount.Add((int)row.Cells[2].Value);
_MyPrice.Add((decimal)row.Cells[3].Value);
}
....
I'm new to ASP.NET, googled every single form but can't found a better solution. I'm executing a procedure using following code, but no success:
I need to provide Month and Year Values not SelectedIndex to the Stored Procedure.
Thanx in Advance.
protected void Page_Load(object sender, EventArgs e)
{
var months = System.Globalization.DateTimeFormatInfo.InvariantInfo.MonthNames;
slMonth.DataSource = months;
slMonth.DataBind();
ListItem li = new ListItem();
li.Text = "-Select Month-";
li.Value = "-1";
slMonth.Items.Insert(0, li);
slMonth.SelectedIndex = 0;
slYear.Items.Insert(0, "-Select Year-");
int index = 1;
for (int Year = 2000; Year <= DateTime.Now.Year; Year++)
{
ListItem liYear = new ListItem(Year.ToString(), Year.ToString());
slYear.Items.Insert(index, liYear);
index++;
}
}
protected void Update_Spend(object sender, System.EventArgs e)
{
SqlConnection SQLConn = new SqlConnection (#"Data Source=RFMMailServ;Database=Acquiring;User Id=sa;Password=+RFM#Pr0300k+;");
SqlCommand cmdUpdate = new SqlCommand("UpdatetblRPT_Spend", SQLConn);
cmdUpdate.CommandType = CommandType.StoredProcedure;
cmdUpdate.Parameters.Add("#Month", SqlDbType.Int).Value = slMonth.SelectedIndex;
cmdUpdate.Parameters.Add("#Year", SqlDbType.VarChar).Value = slYear.SelectedIndex;
SQLConn.Open();
cmdUpdate.ExecuteNonQuery();
LastMsg.Text = "Spend updated successfully.";
}
Try selectedvalue not selectedindex
You are adding the listbox index, not the value. Also, you are assigning int Year to a varchar type Db column. Please make sure to mention what errors/output you've got while executing your code. It'll save us some time.
Try this instead:
protected void Update_Spend(object sender, System.EventArgs e)
{
SqlConnection SQLConn = new SqlConnection (#"Data Source=RFMMailServ;Database=Acquiring;User Id=sa;Password=+RFM#Pr0300k+;");
SqlCommand cmdUpdate = new SqlCommand("UpdatetblRPT_Spend", SQLConn);
cmdUpdate.CommandType = CommandType.StoredProcedure;
cmdUpdate.Parameters.Add("#Month", SqlDbType.Int).Value = int.Parse(slMonth.SelectedValue);
cmdUpdate.Parameters.Add("#Year", SqlDbType.VarChar).Value = slYear.SelectedValue;
SQLConn.Open();
cmdUpdate.ExecuteNonQuery();
LastMsg.Text = "Spend updated successfully.";
}
I've figure out the problem, see the code below, now there is one thing, that on localhost the Year Combo is displaying the list for Single time, but when I execute the solution on client machine, the Year Combo display the values twice?
protected void Page_Load(object sender, EventArgs e)
{
if (this.slMonth.Items.Count <= 0)
for (int i = 1; i <= 12; i++)
{
slMonth.Items.Add(new ListItem(
System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i),
i.ToString()
));
}
ListItem li = new ListItem();
li.Text = "-Select Month-";
li.Value = "0";
slMonth.Items.Insert(0, li);
slYear.Items.Insert(0, "-Select Year-");
int index = 1;
for (int Year = 2000; Year <= DateTime.Now.Year; Year++)
{
ListItem liYear = new ListItem(Year.ToString(), Year.ToString());
slYear.Items.Insert(index, liYear);
index++;
}
}
protected void Update_Spend(object sender, System.EventArgs e)
{
SqlConnection SQLConn = null;
try
{
SQLConn = new SqlConnection(#"Data Source=./;Database=ACQ;User Id=sa;Password=PWD;");
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.CommandType = CommandType.StoredProcedure;
cmdUpdate.CommandText = "UpdatetblRPT_Spend";
cmdUpdate.Connection = SQLConn;
cmdUpdate.Parameters.Add("#Month", SqlDbType.Int).Value = slMonth.SelectedValue;
cmdUpdate.Parameters.Add("#Year", SqlDbType.Int).Value = slYear.SelectedValue;
SQLConn.Open();
cmdUpdate.ExecuteNonQuery();
LastMsg.Text = "Spend updated successfully.";
}
catch (Exception ex)
{
}
finally
{
SQLConn.Close();
}
}