I am trying to insert record into two tables and fetch the UserId of first table and insert into another column of the same table and also into another table but it appears that when I insert data into the tables, the Id of the user is returned and inserted into the second table but inserted a different integer into another column of same first table.
For example, I have UserTable and WalletTable and I want to insert records simultaneously into the two tables and at the same time fetch the Id of UserTable and insert into columns of both tables.
Here is the structure of the first table: I want to fetch UserID in UserTable and insert into CreatedBy of UserTable and UserID of WalletTable. But after inserting, I discovered that integer -1 is inserted into the CreatedBy column of UserTable and in WalletTable the correct UserID is inserted.
How can I correct this please?
UserTable:
UserID | email | pass | con_pass | UserRole | Name | CreatedBy | image | CreateDate
WalletTable:
Id | UserID | email | Name | amount
Here is my insert code (C#)
if (mailtxtbx.Text != "" & pass.Text != "" & conpass.Text != "" & txtname.Text !="")
{
if (pass.Text == conpass.Text)
{
if (Filedoc.PostedFile.FileName != "")
{
if (check1.Checked)
{
int Uid = -1;
byte[] image;
Stream s = Filedoc.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
image = br.ReadBytes((Int32)s.Length);
// define query to be executed
string query = #"INSERT INTO Users (email, pass, con_pass, UserRole, Name, CreatedBy, image, CreateDate) VALUES (#email, #pass, #con_pass, #UserRole, #Name, #CreatedBy, #image, #CreateDate);
SELECT SCOPE_IDENTITY();";
// set up SqlCommand in a using block
using (SqlCommand objCMD = new SqlCommand(query, con))
{
// add parameters using regular ".Add()" method
objCMD.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = mailtxtbx.Text.Trim();
objCMD.Parameters.Add("#pass", SqlDbType.VarChar, 100).Value = pass.Text.Trim();
objCMD.Parameters.Add("#con_pass", SqlDbType.VarChar, 50).Value = conpass.Text.Trim();
objCMD.Parameters.Add("#UserRole", SqlDbType.VarChar, 50).Value = 'A';
objCMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = txtname.Text.Trim();
objCMD.Parameters.Add("#CreatedBy", SqlDbType.Int, 50).Value = Uid;
objCMD.Parameters.Add("#image", SqlDbType.VarBinary).Value = image;
objCMD.Parameters.Add("#CreateDate", SqlDbType.DateTime, 100).Value = DateTime.Now;
// open connection, execute query, close connection
con.Open();
object returnObj = objCMD.ExecuteScalar();
if (returnObj != null)
{
int.TryParse(returnObj.ToString(), out Uid);
}
cmd.ExecuteNonQuery();
}
con.Close();
if (Uid > 0)
{
query = #"INSERT INTO UserWallet (Uid, email, Name, amount) VALUES (#Uid, #email, #Name, #amount)";
using (SqlCommand objCMD = new SqlCommand(query, con))
{
// add parameters using regular ".Add()" method
objCMD.Parameters.Add("#Uid", SqlDbType.Int, 50).Value = Uid;
objCMD.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = mailtxtbx.Text.Trim();
objCMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = txtname.Text.Trim();
objCMD.Parameters.Add("#amount", SqlDbType.Float, 100).Value = 0; //Change type here accordingly
con.Open();
object returnObj = objCMD.ExecuteScalar();
if (returnObj != null)
{
int.TryParse(returnObj.ToString(), out Uid);
}
cmd.ExecuteNonQuery();
lblsuccess.Visible = true;
Div1.Visible = true;
lblsuccess.Text = "Successfully signed up";
lblsuccess.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = false;
dvMessage.Visible = false;
mailtxtbx.Text = "";
pass.Text = "";
conpass.Text = "";
txtname.Text = "";
// Response.Redirect("Default.aspx");
}
}
con.Close();
}
}
}
}
Related
I am creating a WPF application with a MySQL database, I wrote the following code so that the username would be displayed in the Lable, but for some reason it gives me only the last user in my database. How can I make it so that I would log into the account and see information only on it? Those. I go under user 1 and I will see user 1 in the field, and for example not user 101
"server=; username=; password=; database=u1831430_excurtion";
MySqlConnection connectionString = new MySqlConnection(conn);
MySqlCommand command = connectionString.CreateCommand();
command.CommandText = $"SELECT `FirstName` FROM `Login` WHERE 1";
command.CommandText = $"SELECT `LastName` FROM `Login` WHERE 1";
//command.CommandText = $"SELECT `ID` FROM `Login` WHERE 1";
MySqlDataReader myReader;
try
{
connectionString.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
//ID_Label.Content = myReader[0].ToString();
FN_Label.Content = myReader[0].ToString();
LN_Label.Content = myReader[0].ToString();
}
}
I tried to add a field with an ID, but after I did that, all my Labels began to fill in with the last ID from the table
To make it possible to display the last name and first name, you need:
Create a class where variables will be stored:
user ID
Username
public class global
{
public static int userid;
public static string username;
}
Next, when checking strings for fullness, you need to declare variables and translate them into a string
DB db = new DB();
string userName = TB_Name.Text;
string userPass = PB_Password.Password;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM Login WHERE Login = #uL AND Password = #uP AND Role = 2" , db.GetConnection());
command.Parameters.Add("#uL", MySqlDbType.VarChar).Value = userName;
command.Parameters.Add("#uP", MySqlDbType.VarChar).Value = userPass;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
global.userid = Convert.ToInt32(table.Rows[0]["ID"].ToString());
global.username = table.Rows[0]["Login"].ToString();
UserPanel();
}
After that, in the user line, you need to assign the value of the user ID to your label with the ID
string query = $"SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}";
MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
db.openConnection();
MySqlDataReader myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
FN_Label.Content = myReader.GetString("FirstName");
LN_Label.Content = myReader.GetString("LastName");
}
}
To make it possible to display the last name and first name, you need:
Create a class where variables will be stored:
user ID
Username
public class global
{
public static int userid;
public static string username;
}
Next, when checking strings for fullness, you need to declare variables and translate them into a string
DB db = new DB();
string userName = TB_Name.Text;
string userPass = PB_Password.Password;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM Login WHERE Login = #uL AND Password = #uP AND Role = 2" , db.GetConnection());
command.Parameters.Add("#uL", MySqlDbType.VarChar).Value = userName;
command.Parameters.Add("#uP", MySqlDbType.VarChar).Value = userPass;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
global.userid = Convert.ToInt32(table.Rows[0]["ID"].ToString());
global.username = table.Rows[0]["Login"].ToString();
UserPanel();
}
After that, in the user line, you need to assign the value of the user ID to your label with the ID
string query = $"SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}";
MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
db.openConnection();
MySqlDataReader myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
FN_Label.Content = myReader.GetString("FirstName");
LN_Label.Content = myReader.GetString("LastName");
}
}
create table [User]
(
userId int IDENTITY(1,1) primary key ,
UserName nvarchar(30) unique,
gender nvarchar(2),
check( gender in ('M','F')),
email nvarchar(40),
DOB date
)
create table User_Auth
(
uName nvarchar(30),
foreign key (uName) references [User](UserName),
pass nvarchar(30)
)
ALTER PROCEDURE [dbo].[CHECKREGISTERCREDENTIALSFORUSER]
#USRNAME NVARCHAR(30),
#DATE_OF_BIRTH DATE,
#EMAIL NVARCHAR(50),
#PASSWORD NVARCHAR(50),
#GENDER NVARCHAR(5),
#enterflag int output
AS
BEGIN
SET #enterflag = 0;
IF NOT EXISTS (SELECT UserName FROM [User] u WHERE u.UserName = #USRNAME)
BEGIN
IF (#DATE_OF_BIRTH <= GETDATE())
BEGIN
INSERT INTO [User] (UserName, gender, email, DOB)
VALUES (#USRNAME, #GENDER, #EMAIL, #DATE_OF_BIRTH)
INSERT INTO [User_Auth] (uName, pass)
VALUES (#USRNAME, #PASSWORD)
SET #enterflag = 1;
END
ELSE
BEGIN
PRINT 'invalid birth date entered';
END
END
ELSE
BEGIN
PRINT 'username is taken';
END
END
public static int Signup(string uname, string password, DateTime DOB, string email, string genders)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd;
int result = 0;
try
{
if (con != null && con.State == ConnectionState.Open)
{
cmd = new SqlCommand("CHECKREGISTERCREDENTIALSFORUSER", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#USRNAME", SqlDbType.NVarChar, 30).Value = uname;
cmd.Parameters.Add("#PASSWORD", SqlDbType.NVarChar, 50).Value = password;
cmd.Parameters.Add("#DATE_OF_BIRTH", SqlDbType.Date).Value = DOB;
cmd.Parameters.Add("#GENDER", SqlDbType.NVarChar, 5).Value = email;
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar, 50).Value = genders;
cmd.Parameters.Add("#enterflag", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
result = Convert.ToInt32(cmd.Parameters["#enterflag"].Value);
}
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
result = -1; //-1 will be interpreted as "error while connecting with the database."
}
finally
{
con.Close();
}
return result;
}
Here is the C# code - I can't figure out what is wrong - I get an error. There is not out of bound input in procedure parameters. Size of parameters in stored procedure is same as written in code. It is supposed to return 1 if sign up is successful. Moreover in my procedure I am adding into parent table and then to child table, still I get an error of
Insert statement conflict with foreign key constraint
The values for email and gender are mixed around when you set the parameters, so you're actually setting the email value to the gender in the database and vice versa.
cmd.Parameters.Add("#GENDER", SqlDbType.NVarChar, 5).Value = email;
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar, 50).Value = genders;
should be
cmd.Parameters.Add("#GENDER", SqlDbType.NVarChar, 5).Value = genders;
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar, 50).Value = email;
Additionally, in the User table gender is defined with length 2, but in the stored procedure it is declared length 5. Yet, you use check (gender in ('M', 'F')) which is a single char.
If you're only accepting a single character for gender, you could update both the User table definition and stored proc to accept a single char for gender.
I have looked at similar topics with no luck, it looks (to me) like im doing things correctly but the database is just not being updated.
My function, as below, has the parameter values of 1, "Connor Smith", 5, "New" respectively
[HttpPost, ValidateAntiForgeryToken]
public ActionResult UpdateDevelopmentRequest(int changeID, string evaluator, int priority, string status)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.UpdateDevRequest, Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#changeID", SqlDbType.Int).Value = changeID;
cmd.Parameters.Add("#evaluator", SqlDbType.NVarChar, 30).Value = evaluator;
cmd.Parameters.Add("#priority", SqlDbType.Int).Value = priority;
cmd.Parameters.Add("#status", SqlDbType.NVarChar, 15).Value = status;
//cmd.Parameters.AddWithValue("#changeID", changeID);
//cmd.Parameters.AddWithValue("#evaluator", evaluator);
//cmd.Parameters.AddWithValue("#priority", priority);
//cmd.Parameters.AddWithValue("#status", status);
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
return RedirectToAction("DevelopmentRequests");
}
My stored procedure is as below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_UpdateDevRequests]
#changeID INT,
#evaluator NVARCHAR(30),
#priority INT,
#status NVARCHAR(15)
AS
UPDATE it_ChangeRequest
SET it_ChangeRequest.Evaluator = #evaluator,
it_ChangeRequest.Status = #status,
it_ChangeRequest.Priority = #priority
WHERE ChangeID = #changeID
Aside from the code and stored procedure as shown, I have tried to add
int result = cmd.ExecuteNonQuery();
which returned a 1 when values were correct and a 0 when they were incorrect (I am only expecting 1 row to be changed). I have also ran the query separately, hardcoding the values in e.g Declare #changeID int = 1 and the query worked fine with this method too.
I have been stumped on this all morning and would appreciate some help
e: I also tried setting the stored procedure to just priority = 2 instead of priority = #priority to ensure it was pointed and updating the expected DB and all worked as expected when doing that
Please try changing your POST action as below by specifying ParameterDirection:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult UpdateDevelopmentRequest(int changeID, string evaluator, int priority, string status)
{
using (var conn = new SqlConnection(<your_connection_string_goes_here>))
using (SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.UpdateDevRequest, Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
/*
cmd.Parameters.Add("#changeID", SqlDbType.Int).Value = changeID;
cmd.Parameters.Add("#evaluator", SqlDbType.NVarChar, 30).Value = evaluator;
cmd.Parameters.Add("#priority", SqlDbType.Int).Value = priority;
cmd.Parameters.Add("#status", SqlDbType.NVarChar, 15).Value = status;
*/
var param1 = cmd.Parameters.AddWithValue("#changeID", changeID);
cmd.Parameters["#changeID"].Direction = ParameterDirection.Input
param1.SqlDbType = SqlDbType.Int
var param2 = cmd.Parameters.AddWithValue("#evaluator", evaluator);
cmd.Parameters["#evaluator"].Direction = ParameterDirection.Input
param2.SqlDbType = SqlDbType.NVarChar
var param3 = cmd.Parameters.AddWithValue("#priority", priority);
cmd.Parameters["#priority"].Direction = ParameterDirection.Input
param3.SqlDbType = SqlDbType.Int
var param4 = cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters["#status"].Direction = ParameterDirection.Input
param4.SqlDbType = SqlDbType.NVarChar
Conn.Open();
// If you want you can specify the Timeout as below
// cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
Conn.Close();
}
return RedirectToAction("DevelopmentRequests");
}
I have a database made up of 2 (more, actually, but only 2 im working with) tables.
The Material table consists solely of the material-number and the description
DPMatNr
DPBezeichnung
The Eigenschaften table is there to hold the properties of the materials.
It uses the columns:
EigenschaftenBezeichnerID
Wert (value)
My problem is: each entry in the Material table needs to have multiple entries in the Eigenschaften table.
For example:
"Material":
DPMatNr = 001,
DPBezeichnung = "Description"
"Eigenschaften":
EigenschaftenBezeichnerID = 1,
Wert = "A4"
EigenschaftenBezeichnerID = 3,
Wert = "80" and so on.
My code currently looks like this:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string query = #"Insert INTO dbo.Material (DPMatNr, DPBezeichnung)
VALUES (#matnummer, #bezeichnung)";
string query2 = #"Insert INTO dbo.Eigenschaften
(EigenschaftenBezeichnerID, Wert)
VALUES (#1, #format, #2, #grammatur, #3, #gewicht,
#4, #eform, #5, #kuvertierung,
#6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cn.Open();
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
Now I currently get an error that says:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Material' with unique index 'IX_MatNrUnique'
What am I doing wrong?
The Problem here is, that for every "Eigenschaft" you insert into the table you also try to create an entry in the "Material" table. But since every material should only be inserted once (therefore the primary key) you get the error.
Edit:
You could adjust your method like the following:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string check = "Select COUNT(*) FROM dbo.Material where DPMatNr = #matnummer";
string query = "Insert INTO dbo.Material (DPMatNr, DPBezeichnung)" + "VALUES (#matnummer, #bezeichnung)";
string query2 = "Insert INTO dbo.Eigenschaften (EigenschaftenBezeichnerID, Wert)" + "VALUES (#1, #format, #2, #grammatur, #3, #gewicht, #4, #eform, #5, #kuvertierung, #6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand chkCom = new SqlCommand(check, cn))
{
cn.Open();
chkCom.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
int? matCnt = chkCom.ExecuteScalar() as int?;
if (matCnt == 0 || matCnt == null)
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cmd.ExecuteNonQuery();
}
}
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);