how can i change the text on button at run time after click on hyperlink - asp.net

i have two text-boxes a button and a gridview.
Q.1 When user enter details in the text-boxes and press submit button i want to update grid-view accordingly
Q.2 When user hits "Edit" link which is present in the gridview, i would like to change the text of submit button to Update button.
how can i do that thanks in advance
what i have tried yet:
aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
string ID = Request.QueryString["ID"];
cmd = new SqlCommand("Select * from UserDetails where ID='" + ID + "'", con);
con.Open();
ad = new SqlDataAdapter(cmd);
dt.Clear();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
tbid.Text = ID;
TextBox1.Text = dt.Rows[0][1].ToString();
TextBox2.Text = dt.Rows[0][2].ToString();
}
con.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
string Name = TextBox1.Text;
string Place = TextBox2.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into UserDetails(Name,Place) values('" + Name + "','" + Place + "')";
cmd.Parameters.AddWithValue("#Name", TextBox1.Text);
cmd.Parameters.AddWithValue("#Place", TextBox2.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Record Successfully inserted";
}
con.Close();
btnSubmit.Text = "Update";
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
private void BindGrid()
{
con.Open();
ad = new SqlDataAdapter("Select * from UserDetails", con);
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}

Call a Refresh() doesn't help? I'm not sure about ASP.NET, but you have to do it in Forms.

After the user submits new data you can try to call your bindgrid method again, this way it will rebind after the new data is saved. For the edit piece, GridView has an edit template, you can try using that:
http://msdn.microsoft.com/en-us/library/ms972948.aspx

Related

ASP.Net Server prints data from DB but won't write to DB

I have an issue with the connectionstring or something similiar I assume. since data is printed from DB but won't write to DB using the INSERT Query string.
here's the .cs code part:
protected void Page_Load(object sender, EventArgs e)
{
Load_Data();
}
protected void Load_Data()
{
DataTable dtUsers = new DataTable();
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create sql
string sql = "SELECT Username, Fullname, Email FROM Users;";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// load data to dt
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dtUsers.Load(reader);
con.Close();
// print data to gridview
GridView1.DataSource = dtUsers;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// connect to sql
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
// create query
string sql = "INSERT INTO Users (UserName,Passowrd,Email,FullName) VALUES ('" + txtUsername.Text + "','"+ txtPwd.Text + "','"+ txtEmail.Text + "','" + txtFullName.Text + "');";
// command
SqlCommand cmd = new SqlCommand(sql, con);
// save data to db
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
thank you!

how to add confirmation in if statement

In my gridview I am inserting datas. If items repeated then it will show error message that "item repeated".But now I need to show "item repeated" message and another message that "you need to insert this data". If user press yes then that data need to be inserted.My current code only displays item repeated and cannot permit that data to enter. Here is my code
protected void AddNewCustomer(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string SlNo = (control.FindControl("txtSlNo") as TextBox).Text;
string Code = (control.FindControl("txtcode") as TextBox).Text;
string details = (control.FindControl("txtdetails") as TextBox).Text;
string Qty = (control.FindControl("txtqty") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=xxxxx;Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxxx"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from Qtattemp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
}
else
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Qtattemp] VALUES(#Code,#details,#Qty,#SlNo)";
cmd.Parameters.AddWithValue("#SlNo", SlNo);
cmd.Parameters.AddWithValue("#Code", Code);
cmd.Parameters.AddWithValue("#details", details);
cmd.Parameters.AddWithValue("#Qty", Qty);
con.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
BindData();
con.Close();
}
}
}
}
You need to handle it from code behind see the following link
http://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx

populate gridview on dropdownlist indexchanged

i have gridview which populate date from database i want to change seclected data on dropdown SelectedIndexChanged when i select the first index it selected data from database when i chang selections it get another data try this code but nosense this is my code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
if (ddlTguidedit.SelectedIndex==0)
{
string strQuery = "SELECT [Pdfid],[Arpdf_name],[Arpdf_des],[pdf_date] FROM [books_alaa].[dbo].[Tbl_uploadpdf]";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
else
{
string strQuery = " SELECT Pdfid, Enpdf_name AS Arpdf_name, Enpdf_des AS Arpdf_des, pdf_url, pdf_date FROM Tbl_uploadpdf";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void ddlTguidedit_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlTguidedit.SelectedIndex == 0)
{
string strQuery = "SELECT [Pdfid],[Arpdf_name],[Arpdf_des],[pdf_date] FROM [books_alaa].[dbo].[Tbl_uploadpdf]";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
else
{
string strQuery = " SELECT Pdfid, Enpdf_name AS Arpdf_name, Enpdf_des AS Arpdf_des, pdf_url, pdf_date FROM Tbl_uploadpdf";
SqlCommand cmd = new SqlCommand(strQuery);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
why it doesnt work ??
Remove BindData() from !IsPostBack(). You are loading the grid data on DropDownList SelectedIndexChanged. There is no need of BindData() function to be in !IsPostBack(). BindData() function always loads no matter at what index the DropDownList is, it will always take the index as 0.

I have error in updating records in database sql server

I have a problem : I have page for insert data into database , and the same page for update data based on query string for each item , the problem when i update the fields from textbox(s) , the same data is returned to update: the same data updated in database from textbox in page_load !!
In Page_Load
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
protected void Btn_addItem_Click(object sender, EventArgs e)
{
if (Btn_addItem.Text.Equals("Add Item"))
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", "-1");
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item added....";
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", Request.QueryString["id"]);
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item edited....";
con.Close();
}
}
If I understand your question correctly "You are not able to update the DB with the new value you enter in the textboxes. Its updating the DB with the old value again".
You need to check for !IsPostback in your Page_Load as the code for binding the textboxes from DB will be called before Btn_addItem_Click during postback and it will set the value of textboxes back to the old value from DB. See below updated code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
}
}
Hope it helps.

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

Resources