ASP.net Control in FormView ItemTemplate - c#

I have a DropDownList control in ItemTemplate of FormView_Product, how do I modify the code below to reference to my DropDownList1?
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
Code
}
protected void btnBuy_Click(Object sender, EventArgs e)
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Server.MapPath("~/App_Data/webBase.mdb");
OleDbCommand cmd;
//insert item purchased to itemsTable
int intOrderNo = (int)Session["sOrderNo"];
FormViewRow row0 = FormView_Product.Row;
String strProductId = ((Label)row0.FindControl("lblProductId")).Text;
Int32 unitPrice = Convert.ToInt32(((Label)row0.FindControl("lblUnitPrice")).Text);
float floUnitPrice = float.Parse(strUnitPrice);
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
int intQty = int.Parse(strQty);
string strSQL = "INSERT INTO itemsTable(iOrderNo, iProductId, iQty, iUnitPrice)"
+ "VALUES (#OrderNo, #ProductId, #Qty, #UnitPrice)";
cmd = new OleDbCommand(strSQL, mDB);
cmd.Parameters.AddWithValue("#OrderNO", intOrderNo);
cmd.Parameters.AddWithValue("#ProductId", strProductId);
cmd.Parameters.AddWithValue("#Qty", intQty);
cmd.Parameters.AddWithValue("#UnitPrice", floUnitPrice);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
Response.Redirect("ShoppingCart.aspx");
}
}
}

Try This
DropDownList DropDownList1 = (DropDownList)FormView_Product.FindControl("DropDownList1");
String strQty = DropDownList1.SelectedValue;

Related

I am not able to rectify this following error : System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'OAT'

protected void btnDeleteVenue_Click(object sender, EventArgs e)
{
try
{
con.Open();
string ddl = DropDownList1.SelectedItem.Value;
string sq = "select venue_name from Venue";
cmd = new SqlCommand(sq, con);
SqlDataReader r = cmd.ExecuteReader();
string dq = null;
if (r.HasRows)
{
while (r.Read())
{
if (ddl.Equals(r.GetValue(0).ToString()))
{
string dq = "DELETE from Venue WHERE venue_name=" + ddl;
//.Close();
cmd = new SqlCommand(dq, con);
cmd.ExecuteNonQuery();
Response.Write("<script> alert('Venue Deleted') </script>");
con.Close();
}
}
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
Change this line to. A string must be quoted.
string dq = "DELETE from Venue WHERE venue_name='" + ddl + "'";

Saving Data entered in gridview using c# and sqlserver

I have a form that has a asp.net gridview contained in it, on page load, I disabled some textboxes of the grid using jQuery.
my save method to the database is not working properly. I removed the grid from the "save" method and it works with the 2 textboxes.
protected void saverecords() {
try {
int suc = 0;
conn = new SqlConnection(connString);
conn.Open();
sqltrans = conn.BeginTransaction();
string sqldelete = "delete from TrainEmpha where TrainCode = '" + txtcode.Text.ToString().Trim() + "'";
SqlCommand comm = new SqlCommand(sqldelete, conn, sqltrans);
comm.ExecuteNonQuery();
comm.Dispose();
string insertgroup = " Insert into TrainEmpha (TrainCode, TrainDesc,disreglev,EmphaLevel,Award1,Award2,Award3,Award4)" +
" Values (#TrainCode, #TrainDesc,#disreglev,#EmphaLevel,#Award1,#Award2,#Award3,#Award4)";
foreach(GridViewRow gvr in gridview.Rows) {
string drplevel = ((DropDownList) gvr.FindControl("drp_grid_lvl")).Text.Trim();
string txttrain = ((TextBox) gvr.FindControl("txttrained")).Text.Trim();
string txtaward_1 = ((TextBox) gvr.FindControl("txtaward1")).Text.Trim();
string txtaward_2 = ((TextBox) gvr.FindControl("txtaward2")).Text.Trim();
string txtaward_3 = ((TextBox) gvr.FindControl("txtaward3")).Text.Trim();
string txtaward_4 = ((TextBox) gvr.FindControl("txtaward4")).Text.Trim();
comm = new SqlCommand(insertgroup, conn, sqltrans);
comm.Parameters.Add("#TrainCode", SqlDbType.VarChar);
comm.Parameters["#TrainCode"].Value = txtcode.Text.Trim();
comm.Parameters.Add("#TrainDesc", SqlDbType.VarChar);
comm.Parameters["#TrainDesc"].Value = txtdescrip.Text.Trim();
comm.Parameters.Add("#disreglev", SqlDbType.VarChar);
comm.Parameters["#disreglev"].Value = drplevel.Trim();
comm.Parameters.Add("#EmphaLevel", SqlDbType.VarChar);
comm.Parameters["#EmphaLevel"].Value = txttrain.Trim();
comm.Parameters.Add("#Award1", SqlDbType.VarChar);
comm.Parameters["#Award1"].Value = txtaward_1.Trim();
comm.Parameters.Add("#Award2", SqlDbType.VarChar);
comm.Parameters["#Award2"].Value = txtaward_2.Trim();
comm.Parameters.Add("#Award3", SqlDbType.VarChar);
comm.Parameters["#Award3"].Value = txtaward_3.Trim();
comm.Parameters.Add("#Award4", SqlDbType.VarChar);
comm.Parameters["#Award4"].Value = txtaward_4.Trim();
suc += comm.ExecuteNonQuery();
comm.Dispose();
}
if (suc > 0) {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Notify", "alert(' RECORDS SAVED SUCCESSFULLY!');", true);
sqltrans.Commit();
} else {
lblDisplayErr.Text = "COULD NOT SAVE";
}

import data from excel to sql using asp.net

when i import data from excel to sql loops dont stop when columns became null, how i do this.
this is my code :-
protected void insertdata_Click(object sender, EventArgs e)
{
OleDbConnection oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("test4.xlsx") + ";Extended Properties=Excel 12.0;");
try
{
OleDbCommand ocmd = new OleDbCommand("select [Notifications],[ReqStart],[Type],[ReqTime],[OrderNum],[FuncLoc],[CustomerCode],[CustomerName],[Rg],[city],[Phone],[Street],[Distrit] from [Sheet1$]", oledbConn);
oledbConn.Open();
OleDbDataReader odr = ocmd.ExecuteReader();
string Notifications = "";
string ReqStart = " ";
string Type = " ";
string ReqTime = " ";
string OrderNum = " ";
string FuncLoc = " ";
string CustomerCode = " ";
string CustomerName = " ";
string Rg = " ";
string city = " ";
string Phone = " ";
string Street = " ";
string Distrit = " ";
while (odr.Read())
{
Notifications = valid(odr, 0);
ReqStart = valid(odr, 1);
Type = valid(odr, 2);
ReqTime = valid(odr, 3);
OrderNum = valid(odr, 4);
FuncLoc = valid(odr, 5);
CustomerCode = valid(odr, 6);
CustomerName = valid(odr, 7);
Rg = valid(odr, 8);
city = valid(odr, 9);
Phone = valid(odr, 10);
Street = valid(odr, 11);
Distrit = valid(odr, 12);
insertdataintosql(Notifications, ReqStart, Type, ReqTime, OrderNum, FuncLoc, CustomerCode, CustomerName, Rg, city, Phone, Street, Distrit);
}
oledbConn.Close();
}
catch(DataException ex)
{
lblmssg.Text = ex.Message;
lblmssg.ForeColor = System.Drawing.Color.Red;
}
finally
{
lblmssg.Text = "Data Inserted Sucessfully";
lblmssg.ForeColor = System.Drawing.Color.Green;
}
}
protected string valid(OleDbDataReader myreader, int stval)
{
object val = myreader[stval];
if (val != DBNull.Value)
{
return val.ToString();
}
else
{
return Convert.ToString(0);
}
}
public void insertdataintosql(string Notifications, string ReqStart, string Type, string ReqTime, string OrderNum, string FuncLoc, string CustomerCode, string CustomerName, string Rg, string city, string Phone, string Street, string Distrit)
{
SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=White_Whale;Integrated Security=True");
using (SqlCommand cmd=new SqlCommand())
{
cmd.Connection = sqlconn;
cmd.CommandText = "insert into Customers(customer_code,customer_name,RgCode,CityCode,Phone,Distriet,Street) values(#customer_code,#customer_name,#RgCode,#CityCode,#Phone,#Distriet,#Street)";
cmd.Parameters.Add("#customer_code", SqlDbType.VarChar, 20).Value = CustomerCode;
cmd.Parameters.Add("#customer_name", SqlDbType.VarChar, 100).Value = CustomerName;
cmd.Parameters.Add("#RgCode", SqlDbType.Int).Value = Convert.ToInt32(Rg);
cmd.Parameters.Add("#CityCode", SqlDbType.Int).Value = Convert.ToInt32(city);
cmd.Parameters.Add("#Phone", SqlDbType.VarChar, 12).Value = Phone;
cmd.Parameters.Add("#Distriet", SqlDbType.VarChar, 12).Value = Distrit;
cmd.Parameters.Add("#Street", SqlDbType.NVarChar, 100).Value = Street;
cmd.CommandType = CommandType.Text;
sqlconn.Open();
cmd.ExecuteNonQuery();
sqlconn.Close();
}
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlconn;
cmd.CommandText = "insert into Notification(notification,type_code,order_Num,funLoc_Code,customer_code) values (#notification,#type_code,#order_Num,#funLoc_Code,#customer_code)";
cmd.Parameters.Add("#notification", SqlDbType.VarChar,30).Value = Notifications;
//cmd.Parameters.Add("#req_start", SqlDbType.Date).Value = DateTime.ParseExact(ReqStart,"dd-MM-yyyy",null);
cmd.Parameters.Add("#type_code", SqlDbType.Int).Value = Convert.ToInt32(Type);
//cmd.Parameters.Add("#ReqTime", SqlDbType.Bit).Value = ReqTime;
cmd.Parameters.Add("#order_Num", SqlDbType.VarChar, 30).Value = OrderNum;
cmd.Parameters.Add("#funLoc_Code", SqlDbType.Int).Value = Convert.ToInt32(OrderNum);
cmd.Parameters.Add("#customer_code", SqlDbType.VarChar, 20).Value = CustomerCode;
cmd.CommandType = CommandType.Text;
sqlconn.Open();
cmd.ExecuteNonQuery();
sqlconn.Close();
}
}
}
One thing you could do is create an array of objects equal to the number of columns in your spreadsheet and then check if all of those values are DBNull using LINQ
object[] dataTest = new object[colCount];
If (dataTest.All(x => x == DBNull.Value))
break;

Fetching next row from access database in VS C# 2010

I have tried the following code but it throws exception "No value given for one or more required parameters".
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while (i <= count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
One mistake is within the select Statement:
You are trying to select an ID which you don't provide.
string cmdstr = "select * from quant_level1 where id = i";
Your select statement should look like:
string cmdstr = "select * from quant_level1 where id = " + i;
Your Loop-counter is/was within your string. It won't be replaced automatically.
try this -
work only if you are using Web Application
protected void Button2_Click(object sender, EventArgs e)
{
int i;
if (ViewState["count"] != null)
i = Convert.ToInt32(ViewState["count"].ToString());
else
i = 2; // assuming that it is your starting point as given in question
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int)com1.ExecuteScalar();
if (i < count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
ViewState["count"] = i.ToString();
}
con1.Close();
}
This will do the trick in your case. happy coding :)
Since you want to fetch next row every time on clicking the button.
int i=2;
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select * from quant_level1 where id ="+i;
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
if(reader.Read())
{
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
i++;
}
con1.Close();
}

"Variable names must be unique within a query batch or stored procedure." error c# asp.net

this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.

Categories