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
Related
private void namecombo_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = '" + this.namecombo.SelectedItem.ToString() + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach(DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
}
this doesn't work at all whats the problem?
You try to do it this way, just adapt it to your needs.
string sql = "SELECT * FROM Customers WHERE LastName = #lastName AND FirstName = #firstName";
UserAccount account = UserAccount.Empty;
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
{
SqlParameter _firstName = new SqlParameter("#firstName", SqlDbType.NVarChar);
SqlParameter _lastName = new SqlParameter("#lastName", SqlDbType.NVarChar);
_firstName.Value = account.FirstName;
_lastName.Value = account.LastName;
cmd.Parameters.Add(_firstName);
cmd.Parameters.Add(_lastName);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
if (dataSet.Tables.Count > 0)
{
if (dataSet.Tables[0].Rows.Count > 0)
{
DataRow row = dataSet.Tables[0].Rows[0];
//fill your properties with the results
}
}
adapter.Dispose();
dataSet.Dispose();
}
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = N'" + this.customergrid.SelectedRows + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach (DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
So far I managed to use Insert command to create a new record inside a table called "Students". This is the code i used:
int ID = int.Parse( TextBox1.Text);
string name = TextBox2.Text;
string gender = TextBox3.Text;
int marks = int.Parse(TextBox4.Text);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
//create data adapter
SqlDataAdapter adapter = new SqlDataAdapter("select * from students",con);
//create sqlcommand to store execute stored procedure
adapter.InsertCommand = new SqlCommand("spInsertStudent",con);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
//create parameter for Return value (#ROWCOUNT)
SqlParameter parameter = adapter.InsertCommand.Parameters.Add("#ROWCOUNT",SqlDbType.Int);
parameter.Direction = ParameterDirection.ReturnValue;
adapter.InsertCommand.Parameters.Add("#ID", SqlDbType.Int, 0, "ID");
adapter.InsertCommand.Parameters.Add("#Name",SqlDbType.NVarChar,50,"Name");
adapter.InsertCommand.Parameters.Add("#Gender",SqlDbType.NVarChar,10,"Gender");
adapter.InsertCommand.Parameters.Add("#TotalMarks",SqlDbType.Int,0,"TotalMarks");
DataSet ds = new DataSet();
//DataTable students = new DataTable();
adapter.Fill(ds,"Students");
DataTable students = ds.Tables["Students"];
DataRow studentRow = students.NewRow();
studentRow["ID"] = ID;
studentRow["Name"] = name;
studentRow["Gender"] = gender;
studentRow["TotalMarks"] = marks;
students.Rows.Add(studentRow);
adapter.Update(ds,"Students");
Now I want to edit a data row. The data will be change if the ID is matched with the ID parameter. This is the stored procedure I'm using:
create procedure updateStudent
#ID int,
#Name varchar(50),
#Gender varchar(10),
#TotalMarks int
AS
BEGIN
update Students set Name = #Name, Gender = #Gender, TotalMarks = #TotalMarks
where ID = #ID
END
and this is the C# code i use in the code behind:
int ID = int.Parse(TextBox1.Text);
string name = TextBox2.Text;
string gender = TextBox3.Text;
int marks = int.Parse(TextBox4.Text);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Students",con);
DataTable dtStudents = new DataTable();
adapter.Fill(dtStudents);
SqlCommand cmd = new SqlCommand("updateStudent",con);
cmd.Parameters.Add("#ID", SqlDbType.Int, 0, "ID").Value = ID;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50, "Name").Value = name;
cmd.Parameters.Add("#Gender", SqlDbType.NVarChar, 10, "Gender").Value = gender;
cmd.Parameters.Add("#TotalMarks", SqlDbType.Int, 0, "TotalMarks").Value = marks;
adapter.UpdateCommand = cmd;
adapter.Update(dtStudents);
}
But after I clicked the Update button on my web form, there is no error message and the data didn't get updated in my database. What have I did wrong here?
I think you should write classes for executing stored procedures. It will be more easier to read and handle. RunQuery method in such a class like DB
private SqlConnection Connection;
public bool Open()
{
try
{
ConnectionString = "your connection string";
Connection = new SqlConnection(ConnectionString);
Connection.Open();
return true;
}
catch (Exception ex)
{
errorMessage = ex.Message;
return false;
}
}
public bool RunQuery(string ProcedureName, SqlParameter[] Parameters)
{
bool res = false;
try
{
SqlCommand Command = new SqlCommand();
Command.CommandText = ProcedureName;
Command.CommandType = CommandType.StoredProcedure;
Command.Connection = Connection;
Command.Parameters.AddRange(Parameters);
Command.ExecuteNonQuery();
res = true;
}
catch (Exception ex)
{
throw ex;
}
return res;
}
And you can call it
SqlParameter[] param= new SqlParameter[4];
param[0] = new SqlParameter("#ID", ID);
param[1] = new SqlParameter("#Name", name);
param[2] = new SqlParameter("#Gender", gender);
param[3] = new SqlParameter("#TotalMarks", marks);
RunQuery("updateStudent", param);
I've literally searched everything and everywhere but somehow this piece of code of mine just won't work no matter what I've tried.
So I have created a database on a SQL server and linked it, tested it, great it works. OK, so the problem is when I'm trying to insert data on a website textbox and have THAT data copied/transferred into my database table. So I only now get an error saying that 'Exception unhandeld and Must declare the scalar variable "#f_name".
I would appreciate it if anyone can assist? Thanks.
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}
//finally
//{
// myConn.Close();
//}
}
Any suggestions to what could have gone wrong?
You have forgotten to add the parameters to your command and you close the connection before the call of the method. I propose you using:
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.Parameters.AddRange(param);//add the parameters
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
myConn.Close();
}
I suggest you use AddWithValue eg
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql =
"INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " +
" (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
cmd.Parameters.AddWithValue("#f_name",hfname);
cmd.Parameters.AddWithValue("#l_name",hlname);
cmd.Parameters.AddWithValue("#email",hemail);
cmd.Parameters.AddWithValue("#comment",hcomment);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}
I recieve the following error when I try to execute this code. But I added it to my commands. Can someone point out the step that overlooked? Thanks.
Procedure or function 'usps_getContactDetails' expects parameter '#aspContactID', which was not supplied.
SqlConnection conn = new SqlConnection(GetConnString());
SqlCommand cmd = new SqlCommand("usps_getContactDetails", conn);
SqlParameter parmContactID = new SqlParameter("#aspContactID", Convert.DBNull);
cmd.Parameters.Add(parmContactID);
parmContactID.Direction = ParameterDirection.Input;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
conn.Open();
DataSet cusDS = new DataSet();
da.Fill(cusDS, "Contacts");
When doing a SqlCommand and calling a stored procedure, you need to implicity set your SqlCommand to be a StoredProcedure.
using(SqlConnection con = new SqlConnection(""))
{
//Set up your command
SqlCommand cmd = new SqlCommand("[Procedure]", con);
cmd.CommandType = CommandType.StoredProcedure;
//Add your parameters
cmd.Parameters.AddWithValue("#aspContactID", "");
//Declare your data adapter
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds, "Contacts");
}
Follow the above format and you should be fine. Your procedure isn't working for one of two reasons, you were missing the line of code which makes your code work in this case is cmd.CommandType = CommandType.StoredProcedure; or because your parameter is DBNull the procedure says it doesn't have any recognition of that parameter. If you have a parameter which can be null or empty in a stored procedure then do the following:
Create Procedure [dbo].[Example]
#Test as Varchar(100) = ''
As
protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenCon()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["DbPrepConnectionString"].ConnectionString.ToString());
try
{
con.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private void SubmitData()
{
OpenCon();
string sp = "sp_InsertRecord";
cmd = new SqlCommand(sp, con);
cmd.CommandType = CommandType.StoredProcedure;
//add parameters...
cmd.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50));
cmd.Parameters.Add(new SqlParameter("#UserId", SqlDbType.Int));
cmd.Parameters.Add (new SqlParameter ("#ProductName",SqlDbType .VarChar,50));
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
//set paarameters....
cmd.Parameters["#Name"].Value = txtName.Text.ToString();
cmd.Parameters["#UserId"].Value = txtUserId.Text.ToString();
cmd.Parameters["#ProductName"].Value = txtProductName.Text.ToString();
cmd.Parameters["#Price"].Value = txtPrice.Text.ToString();
cmd.ExecuteNonQuery();
lblMessage.Text = "data inserted successfully";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitData();
}
private void FindData()
{
OpenCon();
string s = "sp_FindRecord";
cmd = new SqlCommand(s, con);
cmd.Parameters.Add(new SqlParameter("#Id", SqlDbType.Int));
cmd.Parameters["#Id"].Value = txtName.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
ad = new SqlDataAdapter(cmd);
ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
currow = 0;
FillControls();
}
private void FillControls()
{
txtOrderId.Text = dt.Rows[currow].ItemArray[0].ToString();
txtUserId.Text = dt.Rows[currow].ItemArray[1].ToString();
txtProductName.Text = dt.Rows[currow].ItemArray[2].ToString();
txtPrice.Text = dt.Rows[currow].ItemArray[3].ToString();
}
protected void btnFind_Click(object sender, EventArgs e)
{
FindData();
}
}
}'
I've been working on this one since someone teaches me to use gridview to display my search result.
My problem is, I can't even make it work, when I click or hit the search button, nothing happen. I have:
-1 textbox for last name
-2 dropdownlist for the province and city
-and a search(trigger)button
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
}
private void BindGridView(string field)
{
DataTable dt = new DataTable();
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_accredited_providers WHERE DOCTOR_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
}
// NO RECORDS FOUND
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(txtName.Text.Trim());
}
}
I'm new to this, please assist me. Thanks!
You are not using the field string variable that you are passing to BindGridView and you are mismanaging your SQL parameters (adding the same parameter twice and assigning a DropDown object as a parameter value).
You are adding the same parameter twice.
To fix this, remove this line: comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
You are not using the field variable.
To fix this, change this line
param.Value = ddlProvince; // Note: You are assigning a dropdown OBJECT as the value here!
to
param.Value = field;
in your BindGridView function.