I've a webform. On a dropdownlist selectedindexchanged event I run the given code to populate the form with details.
protected void ddlRequest_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tbl_Requests where RequestID = '" + ddlRequest.SelectedItem.Value + "'", conn);
SqlDataAdapter Adpt = new SqlDataAdapter();
DataSet dsrequest = new DataSet();
try
{
Adpt.SelectCommand = cmd;
Adpt.Fill(dsrequest);
foreach (DataRow dr in dsrequest.Tables[0].Rows)
{
string RequesterID = dsrequest.Tables[0].Rows[0]["RequesterID"].ToString();
string OrgID = dsrequest.Tables[0].Rows[0]["OrgID"].ToString();
string CaseID = dsrequest.Tables[0].Rows[0]["CaseID"].ToString();
string PatientFName = dsrequest.Tables[0].Rows[0]["PatientFName"].ToString();
string PatientLName = dsrequest.Tables[0].Rows[0]["PatientLName"].ToString();
string PatientAge = dsrequest.Tables[0].Rows[0]["PatientAge"].ToString();
string PatientGender = dsrequest.Tables[0].Rows[0]["PatientGender"].ToString();
string MedicalCondition = dsrequest.Tables[0].Rows[0]["MedicalCondition"].ToString();
string PatientMoNo = dsrequest.Tables[0].Rows[0]["PatientMoNo"].ToString();
string Remark = dsrequest.Tables[0].Rows[0]["Remark"].ToString();
string RequestStatus = dsrequest.Tables[0].Rows[0]["RequestStatus"].ToString();
ddlRequesterID.SelectedValue = RequesterID;
ddlOrgID.SelectedValue = OrgID;
txtCaseID.Text = CaseID;
txtPatientFName.Text = PatientFName;
txtPatientLName.Text = PatientLName;
txtPatientAge.Text = PatientAge;
txtPatientGender.Text = PatientGender;
txtMedicalCondition.Text = MedicalCondition;
txtPatientMoNo.Text = PatientMoNo;
txtRemark.Text = Remark;
ddlRequestStatus.SelectedValue = RequestStatus;
}
}
catch (Exception ex)
{
}
finally
{
}
}
}
}
Once user updates required fields on submit button click event I want to update the record with the values in various input fields.
with code given below.
protected void btnSubmitReq_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ddlRequest.SelectedValue == "0")
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsRequests", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RequesterID", SqlDbType.Int).Value = ddlRequesterID.SelectedValue;
cmd.Parameters.Add("#OrgID", SqlDbType.Int).Value = ddlOrgID.SelectedValue;
cmd.Parameters.Add("#CaseID", SqlDbType.NVarChar).Value = txtCaseID.Text;
cmd.Parameters.Add("#PatientFName", SqlDbType.NVarChar).Value = txtPatientFName.Text;
cmd.Parameters.Add("#PatientLName", SqlDbType.NVarChar).Value = txtPatientLName.Text;
cmd.Parameters.Add("#PatientAge", SqlDbType.NVarChar).Value = txtPatientAge.Text;
cmd.Parameters.Add("#PatientGender", SqlDbType.NVarChar).Value = txtPatientGender.Text;
cmd.Parameters.Add("#MedicalCondition", SqlDbType.NVarChar).Value = txtMedicalCondition.Text;
cmd.Parameters.Add("#PatientMoNo", SqlDbType.NVarChar).Value = txtPatientMoNo.Text;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = txtRemark.Text;
cmd.Parameters.Add("#RequestStatus", SqlDbType.NVarChar).Value = ddlRequestStatus.SelectedValue;
cmd.Parameters.Add("#strOwner", SqlDbType.VarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#dbTstamp", SqlDbType.DateTime2).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
else
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUpdRequests", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#RequesterID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequesterID.SelectedValue);
cmd.Parameters.Add("#OrgID", SqlDbType.Int).Value = Convert.ToInt32(ddlOrgID.SelectedValue);
cmd.Parameters.Add("#CaseID", SqlDbType.NVarChar).Value = txtCaseID.Text;
cmd.Parameters.Add("#PatientFName", SqlDbType.NVarChar).Value = txtPatientFName.Text;
cmd.Parameters.Add("#PatientLName", SqlDbType.NVarChar).Value = txtPatientLName.Text;
cmd.Parameters.Add("#PatientAge", SqlDbType.NVarChar).Value = txtPatientAge.Text;
cmd.Parameters.Add("#PatientGender", SqlDbType.NVarChar).Value = txtPatientGender.Text;
cmd.Parameters.Add("#MedicalCondition", SqlDbType.NVarChar).Value = txtMedicalCondition.Text;
cmd.Parameters.Add("#PatientMoNo", SqlDbType.NVarChar).Value = txtPatientMoNo.Text;
cmd.Parameters.Add("#Remark", SqlDbType.NVarChar).Value = txtRemark.Text;
cmd.Parameters.Add("#RequestStatus", SqlDbType.NVarChar).Value = ddlRequestStatus.SelectedValue;
cmd.Parameters.Add("#strOwner", SqlDbType.NVarChar).Value = User.Identity.Name;
cmd.Parameters.Add("#dbTstamp", SqlDbType.DateTime2).Value = DateTime.Now;
cmd.Parameters.Add("#Original_RequestID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequest.SelectedValue);
cmd.Parameters.Add("#RequestID", SqlDbType.Int).Value = Convert.ToInt32(ddlRequest.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
This doesn't update the record.
Pls help.
Resolved.
I was putting EnableViewState="false" in ddlRequest which was causing this issue. I removed it. Now everything working fine.
Thanks.
Related
This is not a question but a solution since I spent a lot of time figuring it out.
Use the onInsert, OnUpdating, OnDeleting events **I used a Datasource for the Populating the grid so that my fields are editable.
2.Row inserting
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spINSERTtblPARfinancialPropotions";
cmd.Parameters.Add("#financialPropotionsPercentageType", SqlDbType.NVarChar).Value = e.NewValues["financialPropotionsPercentageType"].ToString();
cmd.Parameters.Add("#financialPropotionsPercentage", SqlDbType.NVarChar).Value = Convert.ToDecimal(e.NewValues["financialPropotionsPercentage"]);
cmd.Connection = con;
try
{
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
e.Cancel = true;
grid1.CancelEdit();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}```
3.Row Updating
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spUPDATEtblPARfinancialPropotions";
/// cmd.Parameters.Add("#TestConfigId", SqlDbType.Int).Value = Convert.ToInt32(e.NewValues["TestConfigId"]);
//cmd.Parameters.Add("#ServiceId", SqlDbType.Int).Value = Convert.ToInt32(_serviceId);
//cmd.Parameters.Add("#ParentTest", SqlDbType.NVarChar).Value = ddlService.SelectedItem.Text.Trim();
// cmd.Parameters.Add("#MainTest", SqlDbType.NVarChar).Value = e.NewValues["MainTest"].ToString();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = e.OldValues["ID"];
cmd.Parameters.Add("#financialPropotionsPercentageType", SqlDbType.NVarChar).Value = e.NewValues["financialPropotionsPercentageType"].ToString();
cmd.Parameters.Add("#financialPropotionsPercentage", SqlDbType.NVarChar).Value = Convert.ToDecimal(e.NewValues["financialPropotionsPercentage"]);
cmd.Connection = con;
try
{
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
e.Cancel = true;
grid1.CancelEdit();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}```
How to achieve the requirements below:
The Retrieve button click event:
if user doesn't enter CustID in txtCustID need to inform them to enter Customer Id via lblMessage;
if entered CustId doesn't exist in database inform user that it doesn't exist via lblMessage.
The Update button click event - need to ensure that Customer ID already exists in the database.
The Delete button click event: same requirements as for Retrieve button.
I must use error/exception handling (try-catch) to achieve these (project requirement). I spent hours trying, but no success. I would be very grateful for some help! My code is below:
namespace ACME
{
public partial class Customer : System.Web.UI.Page
{
SqlConnection conn;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
SqlCommand command = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
protected void Clear()
{
txtCustID.Text = "";
txtFirstname.Text = "";
txtSurname.Text = "";
rbtGender.SelectedValue = "";
txtAge.Text = "";
txtAddress1.Text = "";
txtAddress2.Text = "";
txtCity.Text = "";
txtPhone.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
txtEmail2.Text = "";
}
protected void btnNew_Click(object sender, EventArgs e)
{
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataTable table1 = new DataTable();
SqlCommand command1 = new SqlCommand();
Clear();
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
command1.Connection = conn;
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "LargestCustID";
command1.Connection.Open();
int id = (int)command1.ExecuteScalar() + 1;
txtCustID.Text = id.ToString();
command1.Dispose();
conn.Close();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "AddCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
lblMessage.Text = "The new record has been added to the database!";
command.Connection.Close();
Clear();
}
protected void btnRetrieve_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "GetCustID";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.SelectCommand = command;
adapter.Fill(table);
int id = table.Rows.Count;
if (id == 0)
{
lblMessage.Text = "Customer ID does not exists!";
}
else
{
lblMessage.Text = "";
txtFirstname.Text = table.Rows[0].Field<string>("Firstname");
txtFirstname.DataBind();
txtSurname.Text = table.Rows[0].Field<string>("Surname");
txtSurname.DataBind();
txtAge.Text = table.Rows[0].Field<int>("Age").ToString();
txtAge.DataBind();
txtAddress1.Text = table.Rows[0].Field<string>("Address1");
txtAddress1.DataBind();
txtAddress2.Text = table.Rows[0].Field<string>("Address2");
txtAddress2.DataBind();
txtCity.Text = table.Rows[0].Field<string>("City");
txtCity.DataBind();
txtPhone.Text = table.Rows[0].Field<string>("Phone");
txtPhone.DataBind();
txtMobile.Text = table.Rows[0].Field<string>("Mobile");
txtMobile.DataBind();
txtEmail.Text = table.Rows[0].Field<string>("Email");
txtEmail.DataBind();
}
command.Connection.Close();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateCustomer";
command.Connection.Open();
command.Parameters.AddWithValue("#CustID",
int.Parse(txtCustID.Text));
command.Parameters.AddWithValue("#Firstname", txtFirstname.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Gender", rbtGender.SelectedValue);
command.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
command.Parameters.AddWithValue("#Address1", txtAddress1.Text);
command.Parameters.AddWithValue("#Address2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtCity.Text);
command.Parameters.AddWithValue("#Phone", txtPhone.Text);
command.Parameters.AddWithValue("#Mobile", txtMobile.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
lblMessage.Text = "The record has been updated!";
command.Connection.Close();
Clear();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["dbConnection1"].ConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DeleteCustomer";
command.Connection.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = (int)param.Value;
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text += "Please enter Customer ID!";
}
try
{
lblMessage.Text = "";
SqlParameter param = new SqlParameter();
param.ParameterName = "#CustID";
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Input;
param.Value = int.Parse(txtCustID.Text);
command.Parameters.Add(param);
adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();
int id = table.Rows.Count;
id = (int)param.Value;
lblMessage.Text += "Customer record has been deleted";
command.Connection.Close();
}
catch (Exception ex)
{
lblMessage.Text = "Customer ID doesnot exists!";
}
Clear();
}
public string CustID { get; set; }
}
}
It sounds like you are trying to control flow of your application by use of exceptions. There are many reasons against this approach:
1) Code is difficult to understand and to debug.
2) Throwing exceptions in .Net is expensive.
3) If exception control flow of application how do you differentiate them from a real exceptions (thrown when something doesn't work as expected)?
If, on the other hand, you want to throw an exception when any of the scenarios you listed in the question happens then you can use standard .Net Exception class:
if (string.IsNullOrWhiteSpace(txtCustID.Text))
{
throw new Exception("Id not provided.");
}
Or you can create a custom exception to provide some more specific information:
public class IdNotProvidedException : Exception
{
public string MyCommandName { get; set; }
public IdNotProvidedException(string msg)
: base(msg)
{
}
public IdNotProvidedException(string msg, string myCommandName)
: base(msg)
{
this.MyCommandName = myCommandName;
}
}
And then you initialize and throw your custom exception.
Lastly, there are already places in your code, though not mentioned in your question, that are worth wrapping in a try...catch block. Basically, any place where you connect with the server may result in something unexpected (for instance, the server may not be available).
I want to use the function "MyPlaces". What should I use instead of commandType.StoredProcedure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("MyPlaces", conn);
cmd.CommandType = CommandType.StoredProcedure; //This part gives me an error
string email = Session["oldemailuser"].ToString();
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string s = "<br />";
while (rdr.Read())
{
string name = s + " " + rdr.GetString(rdr.GetOrdinal("name"))
+ " located in ";
string location = rdr.GetString(rdr.GetOrdinal("location"))
+ "  ";
Label lbl_name = new Label();
lbl_name.Text = email;
form1.Controls.Add(lbl_name);
Label lbl_location = new Label();
lbl_location.Text = email;
form1.Controls.Add(lbl_location);
}
}
Hope your sql function name is "Myplaces".If So,Then Modify your code with this :
string email = Session["oldemailuser"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "SELECT MyPlaces(#email)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
On Registration page I have the error
"C# .net ExecuteNonQuery: CommandText property has not been initialized"
But If I give comments to "cmd.ExecuteNonQuery" on Registration page the this error goes to login page. I am unable to register and login on this.
Login Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Web.Security;
public partial class Login : System.Web.UI.Page
{
//SqlConnection con = new SqlConnection("Data Source=LENOVO;Initial Catalog=Onl9Shopping;Persist Security Info=True;User ID=sa;Password=123");
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes;;Pooling=False");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ImageButton4_Click(object sender, ImageClickEventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText="checksecurity ";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#username", Txtusername.Text);
cmd.Parameters.AddWithValue("#password", Txtpassword.Text);
SqlParameter p1 = new SqlParameter("#ret", SqlDbType.Int);
p1.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter("#status", SqlDbType.VarChar, 50);
p2.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p2);
SqlParameter p3 = new SqlParameter("#name", SqlDbType.VarChar, 50);
p3.Direction = ParameterDirection.Output;
cmd.Parameters.Add(p3);
cmd.ExecuteNonQuery();
int r = Convert.ToInt16(cmd.Parameters["#ret"].Value);
string status = cmd.Parameters["#status"].Value.ToString();
string loggedname = cmd.Parameters["#name"].Value.ToString();
if (r == -1)
{
Label1.Text = "Wrong Username";
}
else if (r == -2)
{
Label1.Text = "wrong Password";
}
else
{
Session["name"] = loggedname;
FormsAuthenticationTicket tk = new FormsAuthenticationTicket(1, Txtusername.Text, DateTime.Now, DateTime.Now.AddHours(2), false, status);
string s = FormsAuthentication.Encrypt(tk);
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,s);
Response.Cookies.Add(ck);
Response.Redirect("Welcome.aspx");
}
Label1.Visible = true;
}
}
Registration Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Registartion : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Onl9Shopping;Trusted_Connection=Yes");
protected void Page_Load(object sender, EventArgs e)
{
}
private void getregno()
{
string query = "select max (registrationno) from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
Txtreg.Text = (Convert.ToInt16(ds.Tables[0].Rows[0][0]) + Convert.ToInt16(1)).ToString();
}
protected void btncheck_Click(object sender, EventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
Label1.Text = "Name available";
}
Label1.Visible=true;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
string query = "select username from register";
SqlDataAdapter adp = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
adp.Fill(ds);
int b = 0;
int c = 0;
int a = 0;
a = ds.Tables[0].Rows.Count;
while (a > b)
{
if (ds.Tables[0].Rows[b][0].ToString().Equals(TxtUserName.Text))
{
c = 1;
}
b++;
}
if (c == 1)
{
Label1.Text = "Name already exist !!..";
}
else
{
SqlCommand cmd = new SqlCommand();
string query1 = "Insert into register(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#Name", Txtname.Text);
cmd.Parameters.AddWithValue("#FatherName", Txtfname.Text);
cmd.Parameters.AddWithValue("#Gender", DropDownList1.Text);
cmd.Parameters.AddWithValue("#Address", Txtaddress.Text);
cmd.Parameters.AddWithValue("#Country", Txtcountry.Text);
cmd.Parameters.AddWithValue("#State", Txtstate.Text);
cmd.Parameters.AddWithValue("#City", Txtcity.Text);
cmd.Parameters.AddWithValue("#Pin", Txtpin.Text);
cmd.Parameters.AddWithValue("#Phn", Txtphn.Text);
cmd.Parameters.AddWithValue("#Email", Txtemail.Text);
cmd.Parameters.AddWithValue("#Username", TxtUserName.Text);
cmd.Parameters.AddWithValue("#Password", Txtpassword.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion", DropDownList2.Text);
cmd.Parameters.AddWithValue("#Hint", Txthint.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Txtname.Text = string.Empty;
Txtfname.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txtcountry.Text = string.Empty;
Txtstate.Text = string.Empty;
Txtcity.Text = string.Empty;
Txtpin.Text = string.Empty;
Txtphn.Text = string.Empty;
Txtemail.Text = string.Empty;
TxtUserName.Text = string.Empty;
Txtpassword.Text = string.Empty;
Txtaddress.Text = string.Empty;
Txthint.Text = string.Empty;
Label2.Text = "Data sumitted ";
Label2.Visible = true;
}
}
}
There no commandtype for the click event for ImageButton1:
SqlCommand cmd = new SqlCommand();
string query1 = "Insert intoregister(Name,FatherName,Gender,Address,Country,State,City,Pin,Phn,Email,Username,Password,SecurityQuestion,Hint)values(#Name,#Fathername,#Gender,#Address,#Country,#State,#City,#Pin,#Phn,#Email,#Username,#Password,#SecurityQuestion,#Hint)";
cmd.CommandText = query1;
cmd.CommandType=CommandType.Text;
cmd.Connection = con;
con.Open();
Had the same issue today. You get this exception when the user you are using doesn't have the permissions to use the database. For testing it, you can login with the user using MS SQL Management Studio, and try to execute the query.
Check which groups the user is assigned to, make it a db_owner f.e., and check that it does not belong to db_denydatareader or db_denydatawriter
I am using the following code to bind BusinessID as the DataValueField of the ddlIndustry dropdown. What I want to do is save the selected ID to a different table (Company). I am doing this with ddlIndustry.SelectedValue. For some reason, the first value is always saved (1), and not the selected value. Do you have any ideas as to why this might be happening?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindCountry();
BindIndustry();
}
private void BindCountry()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("countries.xml"));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
ddlCountry.Items.Add(new ListItem(node.InnerText, node.Attributes["code"].InnerText));
ddlCountry.SelectedIndex = 94;
}
}
private void BindIndustry()
{
SqlCommand cmd = null;
SqlConnection conn = new SqlConnection(GetConnectionString());
conn.Open();
cmd = new SqlCommand("Select Industry, BusinessID FROM BusinessType", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddlIndustry.DataSource = ds;
ddlIndustry.DataTextField = "Industry";
ddlIndustry.DataValueField = "BusinessID";
ddlIndustry.DataBind();
//ddlIndustry.Items.Insert(0, new System.Web.UI.WebControls.ListItem("-- Please Select Industry --", "0"));
}
private void ExecuteCompanyDetailsInsert()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO Company (BusinessID, CompanyName, Email, AddressLine1, AddressLine2, Location, Telephone) VALUES "
+ " (#BusinessID, #CompanyName, #Email, #AddressLine1, #AddressLine2, #Location, #Telephone)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[7];
param[0] = new SqlParameter("#BusinessID", SqlDbType.Int);
param[1] = new SqlParameter("#CompanyName", SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#Email", SqlDbType.VarChar, 50);
param[3] = new SqlParameter("#AddressLine1", SqlDbType.VarChar, 50);
param[4] = new SqlParameter("#AddressLine2", SqlDbType.VarChar, 50);
param[5] = new SqlParameter("#Location", SqlDbType.VarChar, 50);
param[6] = new SqlParameter("#Telephone", SqlDbType.VarChar, 50);
param[0].Value = ddlIndustry.SelectedValue;
param[1].Value = company_name.Text;
param[2].Value = company_email.Text;
param[3].Value = address_line_1.Text;
param[4].Value = address_line_2.Text;
param[5].Value = ddlCountry.SelectedItem.Text;
param[6].Value = telephone.Text;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
First of all modify this code, because when your page is postback to server, your industry dropdown bind again and your selected value lost
if (!Page.IsPostBack)
{
BindCountry();
BindIndustry();
}
and then you can get selected value
ddlIndustry.SelectedValue