C# Gridview Search - asp.net

Expert my search function is not working. Not sure where i went wrong.
My code is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=foc; Trusted_Connection=yes;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
Button1_Click(Button1, null);
TextBox1_TextChanged(TextBox1, null);
}
}
protected void BindGrid()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "SELECT MIN([sddoc]) AS[sddoc],[Soldtopt], [tradingname], [REP],MIN([DELTXT]) AS[Preseller Text], SUM(try_cast([Orderqty] as float)) AS[Orderqty],count(distinct Orderqty) as Qtycount , [DlvDate], SUM(try_cast(Netvalue as float)) as Netvalue, count(distinct SDDoc) as Salesdoc , count(distinct case when Netvalue = '0' then 1 else null end) as ZeroValue , count(distinct SDDoc) - count(distinct case when Netvalue = '0' then 1 else null end) As Result FROM [FOC].[dbo].[foc] where dlvdate = #dlvdate GROUP by Soldtopt,tradingname,REP,DlvDate HAVING SUM(try_cast(Netvalue as float)) = 0 and count(distinct SDDoc) = 1 and count(distinct case when Netvalue = '0' then 1 else null end) = 1";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#dlvdate", TextBox1.Text);
cmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
conn.Close();
gvEmployeeDetails.DataSource = ds;
gvEmployeeDetails.DataBind();
}
protected void gvEmployeeDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblEmpID = (Label)e.Row.FindControl("lblEmpID");
GridView gv_Child = (GridView)e.Row.FindControl("gv_Child");
string txtempid = lblEmpID.Text;
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from [FOC].[dbo].[foc] where sddoc=#sddoc";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#sddoc", txtempid);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
gv_Child.DataSource = ds;
gv_Child.DataBind();
}
}

Hi problem is solved by binding the grid with button click.

Related

How to use SQL Data Reader to check quantity in database?

I want to check quantity in the tblProducts with the quantity selected by the user. If the user selects more than in tblProducts, there will be a pop up message and the quantity will not added. If there is available quantity in tblProducts, the user can add the quantity. Do I need to put SP_UpdateCart in both if statement?
if (e.CommandName == "DoPlus")//Check quantity here
{
string PID = (e.CommandArgument.ToString());
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_getUserCartItem", con)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#PID", PID);
cmd.Parameters.AddWithValue("#UserID", UserID);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
int myQty = Convert.ToInt32(dr["Qty"].ToString());
int PQuantity = Convert.ToInt32(dr["PQuantity"].ToString());
if (dt.Rows.Count > 0)
{
if (myQty < PQuantity)
{
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty + 1);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
else if (myQty > PQuantity)//check quantity between tblCart and
tblProducts
{
Response.Write("<script>alert('Please choose quantity less than
stated!');</script>");
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
}
}
dr.Close();
}con.Close();
}
}
}

what could be the cause of my session keeps changing by itself?

I have a news website , each news had an ID in my database table , I choose 4 IDs randomly to put their titles in the "see more" section .. I select the ID by generating a random row number , the problem is when I click on one of the suggested news it takes me to another news randomly ! which makes no sense to me . the weird thing is the other random ID that I'm taken to does exist but not the one that I clicked.
Latelty I noticed this : for example in the "see more" section we have title1 - title2 - title3 - title4 , so I clicked on title1 it takes me to another random news which i didn't click .. now the 4 titles in the "see more" section are different which is normal .. now when I click in title2 it will take me to the current news in title1 ! and so on next time when i click in title1 it will take me to the curent news in title2 . I can't understand the relation
I tried to store the random numbers in another variables (key1,key2..) before putting one of them in the session but It's still the same problem.
I tried also not refreshing the page (I mean depending just the post back).
I tried clearing the season also tried reomving them all before storing the news Id. There is no error messages.
int myrandom1;
int myrandom2;
int myrandom3;
int myrandom4;
string key1;
string key2;
string key3;
string key4;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string key=" ";
key = Session["key"].ToString();
SqlConnection con = new SqlConnection("Data Source=.; initial catalog=celeblogy; integrated security=true");
SqlCommand cmd = new SqlCommand("select * from news where id like '" + key + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "new");
string Titre = ds.Tables["new"].Rows[0][1].ToString();
Titre = Titre.Replace("*", "'");
titre.InnerText = Titre;
string blog = Decode(ds.Tables["new"].Rows[0][2].ToString());
string[] Blogs;
blog = blog.Replace("*", "'");
Blogs = blog.Split('#');
Literal1.Text = Blogs[0];
Image1.Attributes["src"] = "pictures/" + key + "1.jpg";
if (Blogs.Length >= 2)
{
Literal2.Text = Blogs[1];
Image2.Attributes["src"] = "pictures/" + key + "2.jpg";
}
cmd = new SqlCommand("select * from news", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "news");
Random rnd = new Random();
myrandom1 =rnd.Next(ds.Tables["news"].Rows.Count-1);
Image3.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom1][0].ToString()+"1.jpg";
Label1.Text =ds.Tables["news"].Rows[myrandom1][1].ToString().Replace("*","'");
key1 = ds.Tables["news"].Rows[myrandom1][0].ToString();
myrandom2 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image4.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom2][0].ToString() + "1.jpg";
Label2.Text = ds.Tables["news"].Rows[myrandom2][1].ToString().Replace("*", "'");
key2 = ds.Tables["news"].Rows[myrandom2][0].ToString();
myrandom3 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image5.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom3][0].ToString() + "1.jpg";
Label3.Text = ds.Tables["news"].Rows[myrandom3][1].ToString().Replace("*", "'");
key3 = ds.Tables["news"].Rows[myrandom3][0].ToString();
myrandom4 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image6.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom4][0].ToString() + "1.jpg";
Label4.Text = ds.Tables["news"].Rows[myrandom4][1].ToString().Replace("*", "'");
key4 = ds.Tables["news"].Rows[myrandom4][0].ToString();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["key"] =key1;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Session["key"] = key2;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
Session["key"] = key3;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
Session["key"] = key4;
Response.Redirect(Request.RawUrl);
}
picture of the see more section

Gridview not populating by datatable

Below is the code where The four columns("Challan Number","Proposal Number","CTS Number" and "Amount") is obtained from Sql-Database, and the ("Land" and "Ward") values are obtained from respective methods. The values obtaines are correct but still the "ChallanGridview" is not getting populated.
The datarow "dr1" gets populated with the correct required values, but the "ChallanGridview" doesn't shows anything.
public void FillChallanGrid()
{
string query = string.Empty;
string cs = ConfigurationManager.ConnectionStrings["ConStrg"].ConnectionString;
query = CtrlChallenSearch1.GetChallanQuery();
using(SqlConnection con=new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds,"entry");
int x = ds.Tables["entry"].Rows.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Challan Number");
dt.Columns.Add("Proposal Number");
dt.Columns.Add("CTS Number");
dt.Columns.Add("Amount");
dt.Columns.Add("Land");
dt.Columns.Add("Ward");
for(int i=0;i<x;i++)
{
DataRow dr = ds.Tables["entry"].Rows[i];
DataRow dr1 = dt.NewRow();
dr1["Challan Number"] = dr["ReceiptNo"].ToString();
dr1["Proposal Number"] = dr["ProposalNo"].ToString();
dr1["CTS Number"] = dr["CTSNo"].ToString();
dr1["Amount"] = dr["Amount"].ToString();
dr1["Land"] = GetLand(dr["ProposalNo"].ToString());
dr1["Ward"]=GetWard(dr["ProposalNo"].ToString());
dt.Rows.Add(dr1);
}
ChallanGridView.DataSource = dt;
ChallanGridView.DataBind();
}
}
private object GetLand(string ProposalNumber)
{
string retvalue = string.Empty;
if (ProposalNumber != "" || ProposalNumber != null || ProposalNumber != string.Empty)
{
string[] splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[1];
}
return retvalue;
}
private object GetWard(string ProposalNumber)
{
string retvalue = string.Empty;
string[] splittedvalue = new string[3];
splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[0];
return retvalue;
}
protected void Button1_Click(object sender, EventArgs e)
{
FillChallanGrid();
}
Its solved, I just deleted the present gridview and added another fresh one,
don't know how and why, but the error was gone.
btw thnks Asif.Ali!

need passing two parameters getting with one parameter value

This is my code. I am not able to get my desired output. I should pass parameters and retrieve either with CustomerCode or with CustomerName. Please help me. Thanks in advance and below I placed my sp
protected void txtsearch_Click2(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("spRedemItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CustomerCode", SqlDbType.Int).Value =
(DropDownList2.SelectedItem.Text== "int" ? Convert.ToInt32(txtkey2.Text) :(object)DBNull.Value);
cmd.Parameters.Add("#CustomerName", SqlDbType.NVarChar, 50).Value =
(DropDownList2.SelectedItem.Text == "string" ? txtkey2.Text : (object)DBNull.Value);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["CustomerName"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
Label10.Text = dt.Rows[0]["ItemCode"].ToString();
Label11.Text = dt.Rows[0]["CustomerName"].ToString();
Label12.Text = dt.Rows[0]["PointsNeeded"].ToString();
GridView1.DataBind();
con.Close();
}
--my sp
alter Proc spRedemItem
(
#CustomerCode int=null,
#CustomerName nvarchar(50)=null
)
as
begin
select b.ItemCode,a.CustomerName,c.PointsNeeded from CustomerProfMain a
left join tb_Product b on a.CustomerCode=b.ItemCode
left join tb_RedemptionProducts c on b.Product_ID=c.ID
where (#CustomerCode is null or CustomerCode=#CustomerCode) or (#CustomerName is null or CustomerName=#CustomerName)
end
Instead of using,
where (#CustomerCode is null or CustomerCode=#CustomerCode)
OR (#CustomerName is null or CustomerName=#CustomerName)
you can try changing your WHERE clause like,
where (#CustomerCode is null or CustomerCode=#CustomerCode)
AND
(#CustomerName is null or CustomerName=#CustomerName)

changing label text on selectedindexchanged of dropdown

I need the address (below the dropdown) to change as per the name that is selected in the dropdown... (they are all for one user only)...! (i donno why this keeps saying your post seems only code!!!!!!)
public DataSet BindDropDownListToAUserAddress2()
{
UserFunctions objGetSession = new UserFunctions();
string strSession = objGetSession.GetEmailFromSession();
DataSet dsUserAddress = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "(SELECT FirstName +' '+ LastName as FullName, * FROM AUserAddress inner join AState on AUserAddress.State_ID = AState.ID inner join ACountry on AUserAddress.Country_ID = ACountry.ID inner join AUser on AUserAddress.AUser_ID=AUser.ID where AUser.Email='" + strSession + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(dsUserAddress, "AUserAddress");
con.Close();
return dsUserAddress;
}
protected void ddlName_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dsUserAddress = objBindDDL.BindDropDownListToAUserAddress2();
string strSession = objGetSession.GetEmailFromSession();
ddlName.SelectedValue = "FullName";
if (objBindDDL.BindDropDownListToAUserAddress2() != null && objBindDDL.BindDropDownListToAUserAddress2().Tables.Count > 0)
{
lblDisplayFirstName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["FirstName"].ToString();
lblDisplayLastName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["LastName"].ToString();
lblDisplayAddressLine1.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine1"].ToString();
lblDisplayAddressLine2.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine2"].ToString();
lblDisplayAddressLine3.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine3"].ToString();
lblDisplayCity.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["City"].ToString();
lblDisplayState.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["StateName"].ToString();
lblDisplayCountry.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["CountryName"].ToString();
lblDisplayPostalCode.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["PostalCode"].ToString();
}
}
when you are binding data to dropdown list
ddlStatus.DataTextField = "FullName";
ddlStatus.DataValueField = "Id";
onselected index change event
int ID =Convert.Toint32(ddlName.SelectedValue)
by using this ID select only this ID Record from the dataTable and display

Resources