Page_Load run Button_Click - c#

I have a web-part in SharePoint 2013 which adds the new items from excel. The web-part contains upload control, buttons and textbox. I choose the document from upload control and click the button to load items in SP, if it was successfull I see "Successfull" in textbox or "Not successfull" in another way.
My problem: if i refresh page with web-part, textbox still contains the old text, but i want to see it empty after every refresh.
I try to use Page.IsPostBack, but I think I didn't properly use it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
textbox1.Text = "";
}
protected void btn3_Click(object sender, EventArgs e)
{
if (!Page.IsPostBack)
return;
if(!upload.HasFile)
{
textbox1.Text += "You didn't choose an Excel file";
return;
}
...
}
<asp:Button ID="btn3" runat="server" OnClick="btn3_Click" Text="Add Items" />

In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button click you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}

Related

How to standardize many button events C#

Could you tell me how to put together the many button event.
Writing all the many button event is bad Maintainability.
So I want to turn many button event into one method.
Like this...
Before
private void button1_Click(object sender, EventArgs e)
{
//button1 event
}
private void button2_Click(object sender, EventArgs e)
{
//button2event
}
private void buttonN_Click(object sender, EventArgs e)
{
//buttonNevent
}
After
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
int index = int.Parse(btn.Name.Replace("button", ""));
if(index==1)
{
//button1 event
}
if(index==2)
{
//button2 event
}
}
In ASP.NET Web Forms I've solved this situation like this.
Define a general hidden button (this will be the trigger for all). You should define it "hidden" using the styles.
<asp:Button ID="btnPrintPdf" runat="server" Style="display: none" OnClick="btnPrint_Click" />
For the all other buttons "redirect" the click on the client side to the general one like this:
btnPrintPlan.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NextStepsPlan).ToString()) + ";return false;";
btnPrintNetWorth.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NetWorth).ToString()) + ";return false;";
As you can see, I use a Enum to define what I want to print by clicking different buttons.
The last part is to define the "general" button logic:
protected void btnPrint_Click(object sender, EventArgs e)
{
string sVal = Request.Params["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(sVal))
return;
string[] tks = sVal.Split('|');
if (tks.Length != 2)
return;
string sOrderId = tks[0];
string sPrintType = tks[1];
int orderId = 0;
int iPrintType = 0;
if (!int.TryParse(sOrderId, out orderId) || !int.TryParse(sPrintType, out iPrintType))
return;
string sPdf = null;
if (iPrintType == (int)PrintDocs.NextStepsPlan)
{
....
}//endif
if (iPrintType == (int)PrintDocs.NetWorth)
{
....
}//endif
You could try something like this. Dictionary would be better than if's if you have hundreds of buttons.
private Dictionary<string, Action<object, EventArgs>> buttonEventMap = new Dictionary<string, Action<object, EventArgs>>();
private void setup()
{
buttonEventMap["button1"] = (object sender, EventArgs e)=>{Console.WriteLine("Button 1 Clicked");};
// etc....
}
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
if( buttonEventMap.ContainsKey(btn.Name))
buttonEventMap[btn.Name](sender, e);
}
Although this still is't much different from just implementing each individual ButtonClickEvent.

Clear content from fields after save .net c#

I have aspx form with textboxes and gridview.
When i insert data to textbox it's shows on the gridview after clicking "Save".
I need to clear the content of fieds after i click on "Save".
I tried alot of things and searched in google but nothing works.
I am new at .net.. Can someone help please?
This is my save button fuction:
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
grdvUsers.DataBind();
}
This is my pageLoad:
protected void Page_Load(object sender, EventArgs e)
{
grdvUsers.DataSource = Context1.sp_GetAllUserTest(); // select all users into gridview. datasorce = the data we want to dispaly.
grdvUsers.DataBind();
}
Simply make a method for clearing the controls that you want to clear:
private void ClearControls()
{
txtName.Text =""; // resetting textbox
txtEmail.Tex="";
txtMobile.Text ="";
ddlSomeDropDown.SelectedIndex = -1; // reset dropdown
somecheckBox.Checked = false; // reset checkbox
someRadio.Checked = false; // reset radio
..................
.................
// more controls here
}
and call it after saving :
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
grdvUsers.DataBind();
ClearControls();
}
Just assign text fields a empty string.
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
txtName.Text = String.Empty;
txtEmail.Text= String.Empty;
txtMobile.Text= String.Empty;
txtBirthdate.Text= String.Empty;
grdvUsers.DataBind();
}
You can also do this.
You can clear date and datepicker with DatetimePicker1.Clear(); or with the provided ID

C# combobox if statement + continue button incorporation

This code doesn't work. I don't know what to fix.
public sealed partial class Home : Page
{
public Home()
{
this.InitializeComponent();
ComboBox1.Items.Add("Hindiiiii");
}
string selection = null;
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex!=1)
{
selection = ComboBox1.SelectedItem.ToString();
}
}
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
{
if (selection == "Hindiiiii")
this.Frame.Navigate(typeof(MainPage));
else if (selection == "English")
this.Frame.Navigate(typeof(Home));
}
}
When a user selects Hindiiiii on the main screen and clicks continues he is not redirected to the next page (MainPage).
Let's say your main page looks like this:
You can store the selection in a variable:
string selection = null;
private void ComboBox1_SelectedIndex(object sender, EventArgs e)
{
if (ComboBox1.SelectedIndex!=-1)
{
selection = ComboBox1.SelectedItem.ToString();
}
}
Then in your click event you can pass parameters between your pages:
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
this.Frame.Navigate(typeof(SomePage), selection); //send the contents of the variable to another page
}
And let's say you had another page with a TextBox and a TextBlock:
In your other pages' OnNavigatedTo event, you can retrieve the parameters so you don't have to create a page for every selected language:
string selection = null;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
selection = e.Parameter.ToString();
languageTextBlock.Text = selection; //the textblox is now the selected language
//decide what the contents are based on the selection
if (selection == "English")
translation.Text = "Something in English";
else if (selection == "Hindi")
translation.Text = "Something in Hindi";
else if (selection == "German")
translation.Text = "Something in German";
//etc
}
When you go to the next page, this allows you to create your page based on the selected item. This image demonstrates this:
Alternatively, you can solve your problem by creating a page for every possible language:
private void Continue(object sender, RoutedEventArgs e)
{
if(selection != null)
{
if(selection == "English")
this.Frame.Navigate(typeof(EnglishPage));
else if(selection == "Hindi")
this.Frame.Navigate(typeof(HindiPage));
//and so on
}
}
I prefer to do it this way because it's a lot simpler.
Edit: I see Items in the property box but I'm not aware of how to use it to add combo box items. This is the way that I usually see it done:
Of course you'll need to replace MainPage with your page (if it's not already named MainPage).
Another edit:
If you added the items via the properties panel, you have to access the Content. Use this instead, if you want:
string selection = null;
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ComboBox1.SelectedIndex != -1)
{
//selection = ComboBox1.SelectedItem.ToString();
selection = (ComboBox1.SelectedItem as ComboBoxItem).Content.ToString();
}
}

Asp.net Session state Trying to keep contents of textbox when returned to page

ive two pages, one with a text box and a button, the other with a button a label. What i want to do is to display contents of the textbox on page 1, in the label of the page2 on button click. and then when i click the button to return to page1. preverse whats entered in the textbox on page1. sorry if its confusing. heres my code
page1.aspx
protected void Button1_Click(object sender, EventArgs e)
{
Session["fstName"] = txtBox.Text;
Response.Redirect("Page2.aspx");
}
page2.aspx
protected void Page_Load(object sender, EventArgs e)
{
string a = Session["fstName"].ToString();
lblPage2.Text = a;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
Where do you set the value of the text box when returning to WebForm1.aspx? It should be very similar to what you have for the label on Page2.aspx. Something like:
protected void Page_Load(object sender, EventArgs e)
{
string a = Session["fstName"].ToString();
txtBox.Text = a;
}
At worst, you may need to wrap some error checking around it. Maybe something like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
if (Session["fstName"] != null)
{
string a = Session["fstName"].ToString();
txtBox.Text = a;
}
}

ASPX post back problems with combobox

I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident.
The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view.
The code for this page is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs.
The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button.
The code for this page with this implementation is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
Any help would be gratefully appreciated. TIA
Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback.
You have to populate the list in the section where postbacks flags are checked, just like you do with the grid.
if (IsPostBack == false){
//bind the combobox
}
Otherwise, on a postback, the list will re-populate and the selection will be gone.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

Categories

Resources