This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.
Related
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string selstatus = "select status from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string value = Session["user"].ToString();
DataRow[] row =dt.Select(value);
sda.Fill(ds);
sda.Fill(dt);
if(row!=null){
Label13.Text = ds.Tables[0].Rows[0]["status"].ToString();
}else{
Label13.Text = "No response from mechanic";
}
cmd.ExecuteNonQuery();
con.Close();
I have been finding way to check a specific email id exist in the table. But I can't query what is the correct format to do so. I just need that if a specific email id is available then a message should be displayed.
There is no need for the DataAdapter, DataTable etc. Simply count the number of records
select count(1) from Status where c_email=#c_email
and then on the SqlCommand just use ExecuteScalar:
string selstatus = "select count(1) from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
var count = cmd.ExecuteScalar();
// if count=0 the email doesnt exist
I have 5 data in my datatbase, these data I want to display in a gridView using Data Table. But my code displays only the last binded data in GridView? My code is. Please point out the mistake?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand("select Date from MusterRoll where EmpCode='"+code+"' and Month='1' and Year='2015'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
string date1 = Convert.ToString(row["Date"]);
DateTime date2 = Convert.ToDateTime(date1);
SqlCommand cmd1 = new SqlCommand(" select TOP 1 m.EmpCode,m.NOH,m.OT,m.Late,m.Early,convert(varchar(10),m.Date,103)AS DATE,convert(varchar(10),s1.Shiftname,103)AS Shift From ShiftChange s,ShiftType s1,MusterRoll m WHERE s1.ShiftID=s.NShiftID and '" + date2 + "'>=Fromdate and Todate>='" + date2 + "' and m.Month = '1' and m.date='"+date2+"' and m.EmpCode='Neena' order by Todate desc", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
//var rows1 = ds.Tables[0].Rows;
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow rpw = dt.Rows[rowIndex];
string EmpCode = rpw.Field<string>("EmpCode");
string NOH = rpw.Field<string>("NOH");
string OT = rpw.Field<string>("OT");
string Latae = rpw.Field<string>("Late");
string Early = rpw.Field<string>("Early");
string date3 =rpw.Field<string>("Date");
string Shift = rpw.Field<string>("Shift");
gvSingleemp.Visible = true;
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
}
}
In my shiftChange table there is no Field for date instead of that I have fromDate and ToDate.I want display employee shifft according to MusterRoll table date. So that first I selected MusteRoll date nd checkrd this date exist in between ShiftChange FromDate and ToDate if exist show the Shift
You are databinding the GridView in a loop. You don't need the loop, just bind it to the DataTable:
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
I still think that you don't need those loops at all. I guess that you want to select all records from EmpDetails where the EmpCode = code and MusterRoll.Month='1' and MusterRoll.Year='2015'. Then you only need one sql query to fill one DataTable which can be used as DataSource for gvSingleemp. Is that correct?
If so, this should work (note that i use the using statement and sql-parameters):
DataTable tblData = new DataTable();
string sql = #"SELECT ed.EmpCode,ed.Name,ed.Age,ed.Date
FROM MusterRoll mr
INNER JOIN EmpDetails ed
ON mr.Date = ed.Date
WHERE mr.EmpCode=#EmpCode AND mr.Month=1 AND mr.Year=2015";
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using(var sda = new SqlDataAdapter(sql, conn))
{
var codeParam = new SqlParameter("#EmpCode", SqlDbType.VarChar).Value = code; // change type accordingly
sda.SelectCommand.Parameters.Add(codeParam);
sda.Fill(tblData); // no need for conn.Open/Close with SqlDataAdapter.Fill
}
gvSingleemp.Visible = true;
gvSingleemp.DataSource = tblData;
If you don't want to join the tables you can also use EXISTS:
string sql = #"SELECT ed.EmpCode, ed.Name, ed.Age, ed.Date
FROM EmpDetails ed
WHERE EXISTS
(
SELECT 1 FROM MusterRoll mr
WHERE mr.EmpCode = #EmpCode
AND mr.Month = 1 AND mr.Year=2015
AND mr.Date = ed.Date
)";
You dont have to use loop to bind the DT to GridView :
SqlCommand cmd1 = new SqlCommand(" select EmpCode,Name,Date,Age from EmpDetails where CompanyID='1'", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
gvSingleemp.DataSource =dt;
gvSingleemp.DataBind();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
Da.Fill(data);
gvSingleemp.DataSource = data;
gvSingleemp.DataBind();
I have the following code:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=#username and Password=#password and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Here I want to fetch some values from the table according to a condition,
but when I run this code it shows the following error:
Even though I passed the correct parameters value in #username and #password. How can I resolve this error? Please help.
Try This:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=? and Password=? and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Try This
string query = "Select [UserId],[Firstname],[UserType] from [TBL_USER_LOGIN] where [Username]=? and [Password]=? and [Status]=1";
how am i going prevent "lesson Title" from duplicating in database when user input duplicate data?
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
That kind of uniqueness should be enforced by the database. Add a unique constraint to your table:
CREATE UNIQUE INDEX UK_Lesson_Title ON Lesson (Title)
You can create a function to check the duplicate LessonTitle.
Explanantion: here i have created a function called checkDuplicateTitle().
this function takes AllRows of a LessonTable as DataRowCollection and LessonTitle to be verified as inputs.
it will check the LessonTitle of each and every row.
if given LessonTitle is matched with existing Titles from Table then this function returns true else returns false.
if the returned value is true we will ignore the updating the table with new row as LessonTitle is already Existing otherwise we will add it.
Code as below:
void UpdateLessonTable()
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Project1ConnectionString"].ConnectionString;
cnn.Open();
cmd.CommandText = "select * from Lesson";
cmd.Connection = cnn;
da.SelectCommand = cmd;
da.Fill(ds, "Lesson");
if (!checkDuplicateTitle(ds.Tables["Lesson"].Rows, textBox1.Text.ToString()))
{
DataRow drow = ds.Tables["Lesson"].NewRow();
drow["TopicID"] = DropDownList1.Text;
drow["LessonTitle"] = TextBox1.Text;
drow["LessonDate"] = DateTime.Now;
ds.Tables["Lesson"].Rows.Add(drow);
da.Update(ds, "Lesson");
}
else
{
//you can display some warning here
// MessageBox.Show("Duplicate Lesson Title!");
}
}
//function for checking duplicate LessonTitle
bool checkDuplicateTitle(DataRowCollection rowTitle,String newTitle)
{
foreach (DataRow row in rowTitle)
{
if(row["LessonTitle"].Equals(newTitle))
return true;
}
return false;
}
How To Do This Work on gridviewcomboboxcolumns any idea plx
//Form Load Event
string query="select article_name from article";
SqlCommmand cmd = new SqlCommand(query,con);
SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
combobox1.items.clear();
for(int i=0;i<dt.rows.count;i++)
{
combobox1.items.add(dt.rows[i].cells[0].toString());
}
\ComboBox1 Selected IndexChange Event
string query1="select description from article where article_name='"+combobox1.selectedItem.ToString()+"'";
SqlCommmand cmd1 = new SqlCommand(query1,con);
SqlDataAdapter da1= new SqlDataAdapter(cmd);
DataTable dt1=new DataTable();
da1.Fill(dt1);
combobox2.items.clear();
for(int i=0;i<dt1.rows.count;i++)
{
combobox2.items.add(dt1.rows[i].cells[0].toString());
}
\Now Assume these 2 combox is gridviewCombobox Columns so how to make
this work on gridviewcombobox columns
Project in Windows Form in C#
I m posting this answer after a few months because its helps for
thoose whoose facing problem on DataGridviewComboboxcell
I did my own skill First Fill my first/Main Column
SqlCommand objCmd = new SqlCommand("select distinct article_name from Setup_article_custominvoice", con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
article.DataSource = dt;
//this column1 will display as text
article.DisplayMember = "article_name";
After that i was going on Cell End Edit
if (dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells["article_name"])
{
string CategoryValue = "";
//string CategoryValue1 = "";
if (dataGridView1.CurrentCell.Value != null)
{
CategoryValue = dataGridView1.CurrentCell.Value.ToString();
//CategoryValue1 = dataGridView1.CurrentCell.Value.ToString();
}
//SqlConnection objCon = new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=dbTest3;Integrated Security=True");
string query = "select article_name,composition from Setup_article_custominvoice where article_name='" + CategoryValue + "'";
SqlCommand objCmd = new SqlCommand(query, con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
DataGridViewComboBoxCell t = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2] as DataGridViewComboBoxCell;
t.DataSource = dt;
t.DisplayMember = "composition";
}