accessing values of table in c# using values from other table - c#

I have two tables named myfriends and imageslikes . In my code I am trying to access a column id2 of table myfriends and based on each value in that column I want to access records of imageslikes table. But with my code I am getting only value as output of repeater may be beacause its getting overwritten.
What could be the possible solution for accessing all the records i want to? can someone help?
Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
dt = ds.Tables[0];
dr = dt.Rows[0];
foreach (DataRow row in dt.Rows)
{
string id2 = row["id2"].ToString();
Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
DataList4.DataSource = ds;
DataList4.DataBind();
}

Query = "select * from imageslikes where likedby=(select id2 from myfriends where id1 = '" + Session["id"] + "') ";

Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
dt = ds.Tables[0];
dr = dt.Rows[0];
foreach (DataRow row in dt.Rows)
{
string id2 = row["id2"].ToString();
Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
DataList4.DataSource = ds;
DataList4.DataBind();
//Added this line
ds = new DataSet();
//if you need both records related to id1 and id2 then use
Query = "select * from imageslikes where likedby in ('" + id2 + "', '" + id1 + "')";
//Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
Repeater3.DataSource = ds;
Repeater3.DataBind();
}

Related

c# asp.net check if column in database contains string

In my database, the column is stored as 'Here is jurong', I want to read out the database row if the column contains the word jurong.
I tried using like but it cant work
Here is the code, please help
cmd = new SqlCommand("Select * from Thread WHERE (Delete_Status='No') AND (Thread_Location = '" + searchTB.Text + "' OR Thread_Title = '" + searchTB.Text + "' OR Thread_Description LIKE '%' + #Thread_Description + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#Thread_Description", SqlDbType.VarChar).Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds;
reptater.DataBind();
Does that SQL statement return rows when you run it in the database? Also, I'd be careful of SQL injection attacks when passing values not through parameters.
Should your 'reptater' bind to a DataTable rather than a DataSet?
cmd = new SqlCommand("SELECT * FROM Thread WHERE (Delete_Status='No') AND (Thread_Location = #SearchTxt OR Thread_Title = #SearchTxt OR Thread_Description LIKE '%' + #SearchTxt + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#SearchTxt", SqlDbType.VarChar);
cmd.Parameters["#SearchTxt"].Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds; //ds.Tables[0]; ?
reptater.DataBind();

How can I fix a SqlException incorrect syntax error in my code?

This is code that references a SQL Server database to retrieve to information to be put into a DataGridView.
I get an error:
SqlException [incorrect syntax]
Code:
private void DisplayData()
{
adapt = new SqlDataAdapter("SELECT geoCode, cancer2004" +
"FROM Regional_Intel$" +
"WHERE geoCode LIKE '" + txtDMA.Text + "'", con);
// cmd.Parameters.AddWithValue("#dma", txtDMA.Text);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
How can I fix it?
Add spaces in your SQL string. Also, very bad idea to use string concatenation.
Add spaces like this:
{
adapt = new SqlDataAdapter("Select geoCode, cancer2004 " +
"FROM Regional_Intel$ " +
"where geoCode LIKE '" + txtDMA.Text + "'", con);
//cmd.Parameters.AddWithValue("#dma", txtDMA.Text);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
Use parameters like this:
{
adapt = new SqlDataAdapter("Select geoCode, cancer2004 " +
"FROM Regional_Intel$ " +
"where geoCode LIKE #dma", con);
adapt.SelectCommand.Parameters.Add("#dma", SqlDbType.NVarChar).Value = txtDMA.Text;
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
Separate out your SQL string:
{
var query = #"
SELECT geoCode, cancer2004
FROM Regional_Intel$
WHERE geoCode LIKE #dma";
adapt = new SqlDataAdapter(query, con);
adapt.SelectCommand.Parameters.Add("#dma", SqlDbType.NVarChar).Value = txtDMA.Text;
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}

how to convert dataAndTimePicker value to a string in c#

I need help, I am trying to write a query string that gets data according to a particular date picked in the dataAndTimePicker tool but I keep getting the same exception "Conversion failed when converting date and/or time from character string."
this is the code I tried
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= '" + startDate.Value.ToString("dd/MM/yyyy") + "' and imDate <= '" + endDate.Value.ToString("dd/MM/yyyy") + "'";
SqlDataAdapter da = new SqlDataAdapter(str, declerations.con);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;
Always use parameters instead of putting a values directly into a sql string
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= #StartDate and imDate <= #EndDate";
SqlCommand cmd = new SqlCommand(str, declarations.con);
cmd.Parameters.AddWithValue("#StartDate", startDate.Value);
cmd.Parameters.AddWithValue("#EndDate", endDate.Value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= '" + Convert.ToDateTime(startDate.Value) + "' and imDate <= '" + Convert.ToDateTime(endDate.Value) + "'";
SqlDataAdapter da = new SqlDataAdapter(str, declerations.con);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;

ASP.NET not showing any error, but unable to insert data into database

Under this I am trying to save the cart items chosen by the user into the database, for that I have initially selected the chosen items through Request.Query method now after that I have called those values and formed an SaveCartDetail function in which I have performed insert command into the database,the asp.net shows no error but there is no change in my table the name of my table is cart.
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("totalprice");
dt.Columns.Add("image");
if (Request.QueryString["itemname"] != 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=#items_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("items_name", Request.QueryString["itemname"].ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
if (ds.Tables[0].Rows.Count > 0)
{
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["image"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
int price = Convert.ToInt16(ds.Tables[0].Rows[0]["price"].ToString());
int quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int totalprice = price * quantity;
dr["quantity"] = Request.QueryString["quantity"];
dr["totalprice"] = totalprice;
SaveCartDetail(ds.Tables[0].Rows[0]["item_name"].ToString(), Request.QueryString["quantity"], ds.Tables[0].Rows[0]["price"].ToString(), totalprice.ToString());
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
GridView1.FooterRow.Cells[4].Text = "Total Amount";
GridView1.FooterRow.Cells[5].Text = grandtotal().ToString();
}
}
}
}
private void SaveCartDetail(String itemname, String quantity, String price, String totalprice)
{
String query = "insert into cart(item_name, quantity, price, totalprice, username) values ('" + itemname + "','" + quantity + "','" + price + "','" + totalprice + "','" + Session["username"].ToString() + "')";
SqlConnection scon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon1.Open();
SqlCommand cmd1 = new SqlCommand(query, scon1);
cmd1.ExecuteNonQuery();
scon1.Close();
Response.Write("Items saved in cart");
}

how to display date and time separately in grid view

I have one column in SQL table. which name is Intime. Its data type is nvarchar. It stores both date and time. But I want date and time separately.
I have tried this query:
select AttendanceDate,
SUBSTRING(convert(varchar,intime,113),1,11)[Intime],
SUBSTRING(convert(varchar,intime,113),13,19)[InTime],
InDeviceId,
OutTime,
OutTime,
OutDeviceId,
dbo.MinutesToDuration(duration) as Duration,
Status
from dbo.AttendanceLogs
where EmployeeId=2938
order by AttendanceDate desc
but if I pass same SQL command in grid view its not working.
public void Bind()
{
SqlCommand cmd = new SqlCommand("select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTime],SUBSTRING(convert(varchar,InTime,113),13,19) as [Intime],InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem + " and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
Where possibly could be the problem?
replace your code with this
public void Bind()
{
SqlCommand cmd = new SqlCommand(#"select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTimeD],SUBSTRING(convert(varchar,InTime,113),13,19) as [IntimeT],
InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs
where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem.Value +
" and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
this line not filter any year it return object of drop down list
year(AttendanceDate)=" + ddlYear.SelectedItem + "

Categories