SQL commands not working in C# (ASP.NET web forms) - c#

I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}

Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}

Related

SQL command returning null for value

I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}

ASP.Net C# - Setting a MySQL query and parameters based on a condition

How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

Unable to access selected CheckBoxList Which is dynamically Created

I have searched a lot and failed to and finally arrived here...
I am creating a checkboxList dynamically from the database successfully. Then I want to submit these selcted checked items, I am unable to access. Please find the code....
protected void CreateCheckBoxListDynamically()
{
DataTable dt = new DataTable();
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_GetDomesticCountryList", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
if (ddlTournamentType.SelectedValue != "Select" && ddlTournamentType.SelectedValue != "")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList cblCountry = new CheckBoxList();
cblCountry.ID = "cblCountryTeam";
cblCountry.DataTextField = dt.Columns["CT_CountryTeamName"].ToString();
cblCountry.DataValueField = dt.Columns["CT_CountryTeamId"].ToString();
cblCountry.DataSource = dt;
cblCountry.DataBind();
//phCheckBoxList.Attributes.Add("class", "groupbox");
phCheckBoxList.Controls.Add(cblCountry);
phCheckBoxList.Controls.Add(new LiteralControl("<br />"));
}
dBConnection.Close();
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
// Close data reader object and database connection
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = null;
SqlConnection dBConnection = new SqlConnection();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
string countryTeamIds = "";
try
{
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
cmd = new SqlCommand("SP_AddNewSeries", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#MemberId", SqlDbType.Int).Value = memberId;
if (ddlTournamentType.SelectedValue != "Select")
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = Convert.ToInt32(ddlTournamentType.SelectedValue);
else
cmd.Parameters.Add("#TournamentId", SqlDbType.Int).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesStartDate.Text))
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesStartDate.Text);
else
cmd.Parameters.Add("#SeriesStartDate", SqlDbType.Date).Value = DBNull.Value;
if (!string.IsNullOrEmpty(txtSeriesEndDate.Text))
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = Convert.ToDateTime(txtSeriesEndDate.Text);
else
cmd.Parameters.Add("#SeriesEndDate", SqlDbType.Date).Value = DBNull.Value;
// get values from dynamic controls
CheckBoxList cb = (CheckBoxList)phCheckBoxList.FindControl("cblCountryTeam");
if (cb != null)
{
foreach (ListItem li in cb.Items)
{
if (li.Selected)
countryTeamIds += li.Value + "~";
}
}
if (!string.IsNullOrEmpty(countryTeamIds))
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = countryTeamIds;
else
cmd.Parameters.Add("#CountryTeamIds", SqlDbType.NVarChar).Value = DBNull.Value;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
int i = cmd.ExecuteNonQuery();
//hdnseriesId.Value = cmd.Parameters["#SeriesId"].Value.ToString();
if (i == 0)
{
msgNoRecords.Visible = true;
}
else
{
msgNoRecords.Visible = false;
//Response.Redirect("~/country.aspx", false);
}
dBConnection.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
}
As per you code details object phCheckBoxList has created in aspx page.
If i am right then this will create problem adding checkboxs at server side.
why dont you create only checkbox at server side rather than checkboxLIST.
After creating checkbox you can add is <div>(this has to be declared at aspx page). this <div> should have an ID and make it runat="server" so you can get this.
After doing above task you can easy find every checkbox from that div at server side code.

How do I connect gridview to sql using C# in asp.net?

I know how to connect, open, read, close as you see below. I also have awesome tutorial how to add update/delete etc.
I can connect dataTable to sql using asp.net controls, but I want to learn how to manipulate it from C#.
MasterCust is my gridview table name. How do I connect the to it?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection("Data Source=aserver;Initial Catalog=KennyCust;Persist Security Info=True;user id=sa;pwd=qwerty01");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM MainDB";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}
//MasterCust.
//MasterCust.DataSource = commandString;
//MasterCust.DataBind();
}
Edit: This code worked
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
SqlDataAdapter sdp = new SqlDataAdapter(Cmd);
DataSet ds = new DataSet();
sdp.Fill(ds);
//rdr = Cmd.ExecuteReader();
MasterCust.DataSource = ds.Tables[0];
MasterCust.DataBind();
}
Set the GridView's Datasource property and simply call the DataBind method.
This code will work. ( Tested)
SqlConnection Conn = new SqlConnection("Data Source=Localhost\\SQLEXPRESS;Initial Catalog=Flash2;Integrated Security=True;");
SqlDataReader rdr = null;
string commandString = "SELECT * FROM USER_MASTER";
try
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(commandString, Conn);
rdr = Cmd.ExecuteReader();
MasterCustView.DataSource = rdr;
MasterCustView.DataBind();
}
catch (Exception ex)
{
// Log error
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (Conn != null)
{
Conn.Close();
}
}

MySqlCommand: how to get title into comboboxes

Need help here,
i need to get the title into the comboboxes named cntpaginaBX and prmopaginaBX.
with one it works but when i try both .. It fails.
What i want to know is the "MySqlCommand".
how do i fix it because it doesnt take content, promo, sqlConn togheter.
MySqlConnection sqlConn = new MySqlConnection("Database=joshua;
Data Source=localhost; User Id='root'; Password=''");
string content = "SELECT title FROM content";
string promo = "SELECT title FROM promo";
MySqlCommand myCommando = new MySqlCommand(content, promo, sqlConn); <-----here
MySqlDataReader sqlReader;
object cont;
object prom;
try
{
sqlConn.Open();
sqlReader = myCommando.ExecuteReader();
while (sqlReader.Read())
{
cont = sqlReader.GetValue(0).ToString();
cntpaginaBX.Items.Add(cont);
prom = sqlReader.GetValue(0).ToString();
prmopaginaBX.Items.Add(prom);
}
sqlReader.Close();
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Fout", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
sqlConn.Close();
}
A MySqlCommand is used to run a single query. You cannot simply run two queries together. Each query needs to be a completely separate MySqlCommand.
string content = "SELECT title FROM content";
MySqlCommand contentCommand = new MySqlCommand(content, sqlConn);
try
{
sqlConn.Open();
sqlReader = contentCommand.ExecuteReader();
while (sqlReader.Read())
{
cont = sqlReader.GetValue(0).ToString();
cntpaginaBX.Items.Add(cont);
}
sqlReader.Close();
}
And then:
string promo = "SELECT title FROM promo";
MySqlCommand promoCommand = new MySqlCommand(promo, sqlConn);
try
{
sqlConn.Open();
sqlReader = promoCommand.ExecuteReader();
while (sqlReader.Read())
{
prom = sqlReader.GetValue(0).ToString();
prmopaginaBX.Items.Add(prom);
}
sqlReader.Close();
}

Categories

Resources