After button having postback - c#

protected void Page_Load(object sender, EventArgs e)
{
Button cmdTemp = null;
try
{
cmdTemp = (Button)GetPostBackControl(this);
}
catch { }
FillTableDB();
if(IsPostBack)
{
if(cmdTemp == null || cmdTemp.ID == "btnNew" || cmdTemp.ID != "btnSave")
{
GenerateBlankTableHtml("");
}
}
}
private void FillTableDB()
{
//SQL QUERY
//Select status from table
GenerateBlankTableHtml(status)
}
private void GenerateBlankTableHtml(string status)
{
if(status=="")
{
btnNew.Style.Add("Display", "none");
}
else
{
//show status in label
lblStatus.text=status;
}
}
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if(ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach(string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if(c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
ASPX:
<asp:Button ID="btnSave" runat="server"/>
<asp:Button ID="btnNew" runat="server"/>
<asp:Label ID="lblStatus" runat="server"
I have two functions FillTableDB();GenerateBlankTableHtml(string status);
When status getting blank i have to hide btnNew otherwise showing status in label.
if label having status then and only then New study botton will displayed otherwise not.
What i want when user click on button NEW then and only then i have to show label text with blank status Not click on save button What should i do.

Try this
if(IsPostBack)
{
if(btnNew.Style.Value == "Display:none;")
{
GenerateBlankTableHtml("");
}
}
protected void btnNew_Click(object sender, EventArgs e)
{
GenerateBlankTableHtml("");
}

do something like following.
<asp:Button ID="btnNew" runat="server" onClick="btnNew_click"/>
and now on that button new click.
protected void btnNew_Click(object sender, EventArgs e)
{
Button btnNew = (Button)sender;
btnNew.Style.Add("Display", "none");
lblStatus.text = string.empty;
}

Related

Dynamically created LinkButton OnClick Event not firing on PostBack

I am quite new to ASP and I have been stuck on an issue for about a week. The issue is probably something to do with the Asp Page Life Cycle but I am unable to find how this can be resolved. The issue is that skipto(..) is never called when I click the LinkButton (that were created on first Page Load), which means the LinkButtons are not rendered.
Sample Code below:
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
loadData();
if (!Page.IsPostBack)
{
skiptof();
}
}
public void loadData() {
// Loads from database
}
public void skipto(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn != null)
{
if (btn.CommandArgument != null && btn.CommandArgument != "0")
{
int currPage = 1;
int.TryParse(btn.CommandArgument, out currPage);
skiptof(currPage);
}
}
}
public void skiptof(int currPage = 1)
{
int lastPage = // calculate from LoadData()
string pageDisabled = "";
// pages
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage)
{
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "")
{
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
pagesPageLink.Click += new EventHandler(skipto);
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
// page
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div id="details" runat="server"></div>
<div class="pagination text-center" id="pagination" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
Your problem is:
You didn't bind the data again on postback, I've modified your code a little bit, there are several problems:
in the method skipof:
public void skiptof(int currPage = 1) {
//Clear the controls here then add them again
pagination.Controls.Clear();
int lastPage = // calculate from LoadData()
string pageDisabled = "";
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage) {
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "") {
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
// you can directly assign the method to be called here, there is no need to create a new EventHandler
pagesPageLink.Click += PagesPageLink_Click;
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
You didn't bind the data again in postback, so I modified it:
Page Load:
protected void Page_Load(object sender, EventArgs e) {
//Remove the Page.IsPostBack checking
skiptof();
}
Please take note that the controls you added dynamically will be cleared and you have to add it again on postback to avoid data lost.
Then you'll be able to get the value on PagesPageLink_Click event:
The whole sample is here:
http://pastie.org/10503291

How to change button text on page load based on listview value on Visual Studio

I want to change my button text on page load after retrieving the list view values.
For example,
<asp:Label ID="favouriteLabel" runat="server" Text='<%# Eval("favourite") %>' />
If this label value is 1, the button will change to Favourited.
I have retrieved the list view values by binding the listview
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label activity = (Label)e.Item.FindControl("favouriteLabel");
activityID = activity.Text;
}
}
then, I get the activityID and do a simple if-else check on the page load
protected void Page_Load(object sender, EventArgs e)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
However it does not work. Anybody?
Do that inside a PostBack check in the load event, for instance:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
}
Read more about postback here
Page_Load happens before your ItemDataBound event so the activityId you are looking at in the Page_Load will never be 1.
Just put the code you have in the Page_Load into the ItemDataBoundEvent

calling checkchanged event only upon checking not unchecking

i have CheckChanged event behind Checkbox, it is called whether i tick or un-tick checkbox but i only wat to call this event when check box is checked not on uncheck.
code:
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
HiddenFieldShowHideButtons.Value = "True";
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
This alternate might work
<asp:CheckBox ID="CheckBox1" runat="server" Text="Check"
AutoPostBack="True" OnClick="return chkSelected();"
OnCheckedChanged="CheckBox1_CheckedChanged" />
<script type="text/javascript">
function chkSelected() {
var chk = document.getElementById('<%= CheckBox1.ClientID %>');
if (chk.checked) {
__doPostBack('<%= CheckBox1.ClientID %>', '');
} else {
return false;
}
}
</script>
You can use an if condition to check the state of the Checked property of the CheckBox control. As the following:
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (chkIsHead.Checked)
{
// put your code here
}
}

ASP.NET GridView does not update its row

I followed this tutorial on MSDN for ASP.NET GridView Update Row, but it does not work.
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
Still gives the original value from the cell and not the updated one.
public partial class ManagePage : System.Web.UI.Page
{
BusScheduleModelContainer modelContainer = new BusScheduleModelContainer();
protected void Page_Load(object sender, EventArgs e)
{
//FormsAuthentication.RedirectFromLoginPage()
//if (!HttpContext.Current.User.Identity.IsAuthenticated)
//{
// Server.Transfer("LoginPage.aspx");
//}
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var routeID = int.Parse(e.Values[0].ToString());
var removedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (removedItem != null)
{
modelContainer.BusRoutes.Remove(removedItem);
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
modelContainer.SaveChanges();
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var routeID = int.Parse(e.NewValues[0].ToString());
var updatedItem = modelContainer.BusRoutes.FirstOrDefault(
item => item.RouteID == routeID);
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
}
resultsGridView.EditIndex = -1;
BindData();
}
protected void RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
resultsGridView.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
resultsGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
<div>
<asp:GridView runat="server" ID="resultsGridView"
AutoGenerateColumns="true" AllowPaging="true"
AutoGenerateDeleteButton="true" OnRowDeleting="RowDeleting"
AutoGenerateEditButton="true" OnRowUpdating="RowUpdating"
OnRowEditing="RowEditing" OnRowCancelingEdit="RowCancelingEdit">
</asp:GridView>
</div>
Do you use CommandField for update controler?
If so, when you click update button, first it will do Page_Load event handler, after that do the implementation in RowUpdating event handler.
You should try to check post back in Page_Load event handler like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
resultsGridView.DataSource = modelContainer.BusRoutes.ToList();
resultsGridView.DataBind();
}
}
By this way, it will bind data to the GridView only first time you open this page.
For post back event such as clicking update button, it will not bind the original data to GridView again.
In RowUpdating method you need to add modelContainer.SaveChanges(); like below:
if (updatedItem != null)
{
GridViewRow row = resultsGridView.Rows[e.RowIndex];
var res = row.FindControl("ctl00$ContentPlaceHolder1$resultsGridView$ctl02$ctl03");
updatedItem.DepartureCity = ((TextBox)(row.Cells[2].Controls[0])).Text;
updatedItem.ArrivalCity = ((TextBox)(row.Cells[3].Controls[0])).Text;
updatedItem.DepartureTime = DateTime.Parse(((TextBox)(row.Cells[4].Controls[0])).Text);
updatedItem.ArrivalTime = DateTime.Parse(((TextBox)(row.Cells[5].Controls[0])).Text);
modelContainer.SaveChanges();
}

execute different codes in code behind on confirm ok and cancel using textbox methods and property only

This is the script and I want to use it in code behind previously I used clentclick property of button button I want to use this code without using button
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
what else can I do so that it is achievable for me
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
// TextBox1.Attributes.Add("OnClientClick", "Confirm()");
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//Your logic for OK button
}
else
{
//Your logic for cancel button
}
}
public void OnConfirm(object sender, EventArgs e)
{
}
Leave a button on the page, hide it using css and then call click() from JavaScript after you have set your value:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
document.getElementById("Button1").click();
}
</script>
<asp:TextBox ID="TextBox1" runat="server" onchange="Confirm()"></asp:TextBox>
<div style="display:none;"><asp:Button ID="Button1" ClientIDMode="static" runat="server" onclick="Button1_Clicked" /></div>
Then in your codebehind:
protected void Button1_Clicked(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//Your logic for OK button
}
else
{
//Your logic for cancel button
}
}

Categories