a and c variable's errorNot inserting properly, Invalid column or can't convert to char from int if I add '' to it. Also Hardcoding a value in the string makes it work there.
" and ' have been tried..
int a = Convert.ToInt32(TextBox1.Text);
int c = Convert.ToInt32(TextBox3.Text);
string a3 = a.ToString();
string c3 = c.ToString();
string a2 = TextBox1.Text;
string c2 = TextBox3.Text;
int i1 = 77;
int i2 = 5;
string b = TextBox2.Text;
string d = TextBox4.Text;
string ee = TextBox5.Text;
string f = TextBox6.Text;
string g = TextBox7.Text;
string h = TextBox8.Text;
//RETRIVE VALUES FROM CURRENT BOXES
//(Id,Username,Age,Gender,Contact,Email,City,Password)
string update = dbhelper.ExecuteScalar("INSERT INTO
dbo.UserDetails VALUES(a,'b',c,'d','ee','f','g','h') ");
Action_Performed.Text = "User Details Updated Successfully";
You could solve it by doing something like this, important to use SQL parameters to avoid sql injection through your inputs;
string sql = "INSERT INTO UserDetails(a,b,c) VALUES(#a,#b,#c)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#a", a);
command.Parameters.AddWithValue("#b", b);
command.Parameters.AddWithValue("#c", c);
command.ExecuteNonQuery();
}
Related
I try to extract the results in c# asp.net from my stored procedure but it has 2 recordsets. the first with 1 row and the second with many rows as dates.
The code
public string penth_slqDAYS(string connectionString)
{
string sMonth = DateTime.Now.Month.ToString();
string syear = DateTime.Now.Year.ToString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command1 = new SqlCommand("penthhmera_proc", connection);
/////////////////////////////
SqlParameter param1;
param1 = command1.Parameters.Add("#prs_nmb_pen", SqlDbType.VarChar, 7);
param1.Value = prs_nmb_lb1.Text.Trim();
SqlParameter param2;
param2 = command1.Parameters.Add("#month_pen", SqlDbType.Int);
param2.Value = sMonth;
SqlParameter param3;
param3 = command1.Parameters.Add("#year_int", SqlDbType.Int);
param3.Value = syear;
/////////////////////////
command1.Parameters.Add("#days_out", SqlDbType.Int);
command1.Parameters["#days_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#message_out", SqlDbType.VarChar,50);
command1.Parameters ["#message_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#dateess_out", SqlDbType.Date);
command1.Parameters["#dateess_out"].Direction = ParameterDirection.Output;
///////////////////////////
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
command1.ExecuteNonQuery();
days_penthwork_tx.Text = Convert.ToString(command1.Parameters["#days_out"].Value);
message_tx.Text = Convert.ToString(command1.Parameters["#message_out"].Value);
///the above parameter contains rows with dates
Label12.Text = Label12.Text + Convert.ToString(command1.Parameters["#dateess_out"].Value);
connection.Close();//close connection
}
return "success";
}
catch (Exception e)
{
return e.ToString();
}
}
My SQL Server stored procedure:
the results
and the query when c# run the code
declare #p4 int
set #p4 = 3
declare #p5 varchar(50)
set #p5 = 'some text'
declare #p6 date
set #p6 = NULL
exec penthhmera_proc #prs_nmb_pen = '274484',
#month_pen = 1,
#year_int = 2021,
#days_out = #p4 output,
#message_out = #p5 output,
#dateess_out = #p6 output
select #p4, #p5, #p6
I think that with that way #p6 is always null.
Finally I want to load all the values from the second recordset to a Gridview or something like a table in order to show it in my webform.
Any idea?
Thanks in advance
ExecuteReader was the answer. thnx Charlieface.
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = command1.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//some code
}
dr.NextResult();
while (dr.Read())
{
//some code
}
}
else
{
Console.WriteLine("No data found.");
}
I am inserting values 1,2 and 3 in the 3 column of a gridview and in the fourth column, i am expecting to get the answer as 6 but in the fourth column the values are getting append and the value is like 123 in the fourth column. Below i have pasted the code
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
string ID = (row.Cells[1].Text);
string Assignment_Marks =(row.Cells[2].Controls[0] as TextBox).Text;
string Viva_Marks = (row.Cells[3].Controls[0] as TextBox).Text;
string Midterm_Marks = (row.Cells[4].Controls[0] as TextBox).Text;
string Overall_Marks = (row.Cells[5].Controls[0] as TextBox).Text;
string status = (row.Cells[6].Controls[0] as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["StudentConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE users SET Assignment_Marks = #Assignment_Marks, Viva_Marks = #Viva_Marks, Midterm_Marks = #Midterm_Marks, Overall_Marks= #Overall_Marks, status=#status where div='A' and year='3' and stream='IT' and ID=#ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Assignment_Marks", Assignment_Marks);
cmd.Parameters.AddWithValue("#Viva_Marks", Viva_Marks);
cmd.Parameters.AddWithValue("#Midterm_Marks", Midterm_Marks);
Overall_Marks = Assignment_Marks + Viva_Marks + Midterm_Marks;//It is use to append i know, then what to use
cmd.Parameters.AddWithValue("#Overall_Marks", Overall_Marks);
cmd.Parameters.AddWithValue("#status", status);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
Because all variables are string type, when you plus two string, it will append.
You have to convert string to int type, then it will sum up all numbers.
int SumUp = Int32.Parse(Assignment_Marks) + Int32.Parse(Viva_Marks) + Int32.Parse(Midterm_Marks);
Overall_Marks = SumUp.ToString();
Above mentioned values are stored in string format.So we want to convert the decimal format.Because marks may be in decimal format.eg:70.5
Please tell me below mentioned code is working or not.If this answer is useful to you click the answer option and like.
decimal OM=0m; OM=Convert.ToDecimal(Assignment_Marks)+Convert.ToDecimal(Viva_Marks)+Convert.ToDecimal(Midterm_Marks);
Overall_Marks = OM.ToString();
Is anyone can tell me, why I'm getting error here.
If pass a value to parameters with this line
int qID = 10087;
It works fine, but when I try this line
int qID = Int32.Parse(corr[0]);
It gives me error (failed), rest of code is same in both situations. What could be a problem here?
int pID1 = 102;
//int qID = 10087;
int qID = Int32.Parse(corr[0]);
using (var cn1 = new SqlConnection(WebConfigurationManager.ConnectionStrings["lConn"].ConnectionString))
{
cn1.Open();
string sql1 = "SELECT DISTINCT Q FROM QATXT WHERE S= #pID AND QID=#qID ";
SqlCommand cmd1 = new SqlCommand(sql1, cn1);
cmd1.Parameters.AddWithValue("#pID", pID1);
cmd1.Parameters.AddWithValue("#qID", qID);
SqlDataReader rdr1 = cmd1.ExecuteReader();
if (rdr1.Read())
{
mainQTxt = (string)rdr1.GetValue(0);
}
cn1.Close(); rdr1.Close(); cmd1.Dispose();
}//- End of cn
rep = mainQTxt ;
Try Changing int qID = Int32.Parse(corr[0]); to int qID = Convert.ToInt32(corr[0]);
I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False
Cheers,
Im trying to insert a database value to my string array.
for some reason, it says :
"Object reference not set to an instance of an object."
This is my code :
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
and its refering to this line :
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
Thanks for the helpers!
rnd is null , add a line
rnd = new Random();
at the start of your event
rnd = new Random();
Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.