Distinguish Button click xamarin.forms - xamarin.forms

Hi I have four buttons in my xamarin.forms application.Each button click will open a listview in a Popup.I am trying to open same popup page on each button click.I am using messeging centre for returning the listview selected item back to button page. Where I am stuck is how can I distinguish the button click in popup page?Should I use a flag or somethong?
My Button page
void Button1_Tapped(object sender, EventArgs e)
{
PopupNavigation.PushAsync(new AnswerPopup(tranzaction));
MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
{
string receivedData = value.Myvalue;
Answer1.Text = receivedData;
});
}
void Button2_Tapped(object sender, EventArgs e)
{
PopupNavigation.PushAsync(new AnswerPopup(tranzaction));
MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
{
string receivedData = value.Myvalue;
Answer2.Text = receivedData;
});
}
void Button3_Tapped(object sender, EventArgs e)
{
PopupNavigation.PushAsync(new AnswerPopup(tranzaction));
MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
{
string receivedData = value.Myvalue;
Answer3.Text = receivedData;
});
}
My popup page
private string selectedItem;
private void AnsList_Tapped(object sender, SelectedItemChangedEventArgs e)
{
var selectedCategory = e.SelectedItem as Answer;
if (selectedCategory != null)
selectedItem = selectedCategory.Text;
MessagingCenter.Send(new MyMessage() { Myvalue = selectedItem.ToString() }, "AnsData");
PopupNavigation.PopAsync();
}

first, you don't need to subscribe multiple times, just do it once per page (in the constructor, typically)
second, add a property to MyMessage that will tell you which button as called
MessagingCenter.Subscribe<MyMessage>(this, "AnsData", (value) =>
{
string receivedData = value.Myvalue;
switch (value.Question) {
case "Q1":
Answer1.Text = receivedData;
break;
case "Q2":
Answer2.Text = receivedData;
break;
case "Q3":
Answer3.Text = receivedData;
break;
}
});
finally, when calling AnswerPopup, pass a key for the question (which it will then need to pass back via MyMessage when calling MessagingCenter.Send()
void Button1_Tapped(object sender, EventArgs e)
{
// use "Q2", "Q3", etc as appropriate
PopupNavigation.PushAsync(new AnswerPopup(tranzaction, "Q1"));
}

Related

How to return multiple values from XCT Popup to the main page?

I have two TimePickers and an Editor in my Popup. I can return Editor value to the main page by clicking on a button on popup:
private void Button_Clicked_2(object sender, EventArgs e)
{
Dismiss(editor_value.Text);
}
and add a label to the main page using this code:
private async void Button_Clicked(object sender, EventArgs e)
{
var result = await Navigation.ShowPopupAsync(new popup01());
MyStack.Children.Add(new Label { Text = result.ToString()});
}
I want to return TimePicker01, TimePicker02, and Editor values to the main page at the same time. I need to have 3 labels in the main page, every time I click the button. label01 for TimePicket01 value, label02 for TimePicket02 value, and label03 for Editor.
I tried to use overload including 3 arguments but Dismiss allows just one argument.
Please help me.
I tried to use Arrays. In Popup:
private void Button_Clicked_2(object sender, EventArgs e)
{
string timeString01 = DateTime.Today.Add(Time_Start.Time).ToString(Time_Start.Format);
string timeString02 = DateTime.Today.Add(Time_End.Time).ToString(Time_End.Format);
string time = string.Join("__", timeString01, timeString02);
string total = string.Join(",", time, editor_value.Text);
Dismiss(total);
}
And then:
private async void Button_Clicked(object sender, EventArgs e)
{
var result = await Navigation.ShowPopupAsync(new popup01());
string[] time_text = Convert.ToString(result).Split(',');
MyStack.Children.Add(new Label { Text = time_text[0].ToString() });
MyStack.Children.Add(new Label { Text = time_text[1].ToString(), FontAttributes = FontAttributes.Bold, FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)) });
}

add column value to the row selected in gridview after clicking button send

Im filling my gridview in the code behind using (C#), I have one column called [SO_Status], This column is empty at the begining, I want to change the value of [SO_Status] to "SO already sent" when I click the button Send!
here is a capture of my grid view:
the select code is:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Int16 email;
if ( e.CommandName == "Select")
{
email = Convert.ToInt16(e.CommandArgument);
em.Text = GridView1.Rows[email].Cells[4].Text;
}
}
public void Send_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = "smtp.gmail.com";
client.Port = 587;
....
try
{
client.Send(msg);
ClientScript.RegisterClientScriptBlock(this.GetType(), "validation", "alert('Your Email was sent successfully!');", true);
}
catch
{
Response.Write("Sent error");
}
}
}
I use the select button to get the mail address from the line and send email to this mail address, I want to change the SO_Status after sending this email, to avoid sending email another time to the same person.
You need to update the SO_Status in database and rebind the grid from database.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Int16 email;
if ( e.CommandName == "Select")
{
email = Convert.ToInt16(e.CommandArgument);
em.Text = GridView1.Rows[email].Cells[4].Text;
//send the email
if (Sendmail(em.Text))
{
updateStatus(em.Text);
// rebind the grid.
bindgrid();
}
else
{
// write code to show error message.
}
}
}
private bool Sendmail( string email)
{
// code to send mail
// you can find the code on google.
return returnvalue;
}
private void updateStatus(string email)
{
// Code to update db colomn
}
private void bindgrid()
{
// code to bind grid.
}

How to call ascx delegate to some other ascx btn click?

I have ascx suppose A.ascx in which i am writing a delegate on OnInit() like this
btnUpdate.Click += delegate
{
if (MaxLength.HasValue && txtText.Text.Length >= MaxLength.Value)
{
lblError.Text = string.Format(Resources.ErrorMessage_FieldLength, MaxLength);
return;
}
if (Update != null) Update(this, EventArgs.Empty);
};
Now I want to call this delegate on B.ascx btn click
protected void btnHdnAnswer_Click(object sender, EventArgs e)
{
// How to call above delegate..
}
Please help me in this
Make your delegate a proper method.
btnUpdate.Click += delegate { DoUpdate(); }
...
public void DoUpdate()
{
if (MaxLength.HasValue && txtText.Text.Length >= MaxLength.Value)
{
lblError.Text = string.Format(Resources.ErrorMessage_FieldLength, MaxLength);
return;
}
if (Update != null) Update(this, EventArgs.Empty);
}
Make sure the Id of your control is set to generate a member for it in the code-behind:
<Project:A runat="server" ID="MyBControl"/>
Then call it from your B (parent) control:
protected void btnHdnAnswer_Click(object sender, EventArgs e)
{
MyBControl.Update();
}

Programmatically created CheckBoxList not firing when "unchecked"

I'm using ASP.NET and C#. I'm programmtically creating a checkboxlist. When I check an item, the SelectedIndexChanged event is firing. But, when I uncheck the item, the event is not fired. I'm binding the items on every postback and autopostback is set to true. Where am I going wrong? Here's the code -
page_load
{
var cblUser = new CheckBoxList();
cblUser.AutoPostBack = true;
cblUser.SelectedIndexChanged += cblUser_SelectedIndexChanged;
var list = DAL.GetUsers();
foreach (var user in list)
{
cblUser.Items.Add(new ListItem(user.Name, user.Id));
}
}
Thank you.
Update #1: Actual code -
public partial class CategoriesAccordion : UserControl
{
public List<Community> AllCommunities
{
get
{
if (Session["AllCommunities"] == null)
{
var db = new CommunityGuideDB();
Session["AllCommunities"] = db.Communities.OrderBy(x => x.Name).ToList();
}
return (List<Community>) Session["AllCommunities"];
}
}
public List<Category> Categories
{
get
{
if (Session["Categories"] == null)
{
var db = new CommunityGuideDB();
Session["Categories"] = db.Categories.OrderBy(x => x.Name).ToList();
}
return (List<Category>) Session["Categories"];
}
}
public event EventHandler Categories_Selected = delegate { };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) Session.Remove("Categories");
LoadCategories();
}
private void LoadCategories()
{
foreach (var parent in Categories.Where(item => item.ParentId == null && item.ShowAsPivot == true).OrderBy(x => x.DisplayOrder))
{
var pane = new AccordionPane {ID = parent.Name};
pane.HeaderContainer.Controls.Add(new LiteralControl(parent.Name));
var cblValues = new CheckBoxList();
cblValues.AutoPostBack = true;
cblValues.SelectedIndexChanged += cblValues_SelectedIndexChanged;
foreach (var child in Categories.Where(child => child.ParentId == parent.Id))
{
var communityCount = child.CommunityCategory.Where(x => x.Categories_Id == child.Id).Count();
cblValues.Items.Add(new ListItem(string.Format("{0} ({1})", child.Name, communityCount), child.Id.ToString()));
}
pane.ContentContainer.Controls.Add(cblValues);
acdFilters.Panes.Add(pane);
}
}
protected void cblValues_SelectedIndexChanged(object sender, EventArgs e)
{
var cblValues = ((CheckBoxList) sender);
var selectedCategories = (from ListItem item in cblValues.Items where item.Selected select Categories.Find(c => c.Id == new Guid(item.Value))).ToList();
Categories_Selected(this, new CommandEventArgs("SelectedCategories", selectedCategories));
}
}
I don't get how do you add the control to a container?
I've just checked and I've got the event fired both on checking & unchecking.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckBoxList cbList = new CheckBoxList();
cbList.AutoPostBack = true;
for (int i = 0; i < 10; i++)
cbList.Items.Add(i.ToString());
cbList.SelectedIndexChanged += new EventHandler(cbList_SelectedIndexChanged);
form1.Controls.Add(cbList);
}
void cbList_SelectedIndexChanged(object sender, EventArgs e)
{
//fires both on check & uncheck of an item
}
}
The SelectedIndexChanged event you are bounding is fired upon selecting different item on your list, not when you check an item. CheckBoxList does not have an event for changing the status of its items.
Try a to use list control like Repeater ...

Event Control Not working?

i careate button control and place in panel but not working?
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Test button";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
When you dynamically add controls to your page, you have to re-add them on any subsequent request (postback). The button you added in Button1_OnClick will not automatically be recreated in a subsequent request (e.g. in a postback).
There a lot's of similar questions about this topic, where you can find details. For examples, use the following search:
https://stackoverflow.com/search?q=dynamic+control+event+[asp.net]
Make sure you assign an ID to the button, and make sure it's the same everytime you create it.
Create the control in the CreateChildControls overload, adding it once in response to another event isn't going to be enough to keep it on the page.
You're best bet is going to be tracking the whether the button needs to be created or not:
bool CreateButton
{
get
{
if (ViewState["CreateButton"] == null)
return false;
return (bool)ViewState["CreateButton"];
}
set
{
ViewState["CreateButton"] = value;
}
}
override void public CreateChildControls ()
{
panel1.Controls.Clear ();
if (CreateButton)
{
Button btn = new Button();
btn.Text = "Test button";
btn.ID = "CreatedButton"; // Note the ID here...
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateButton = true;
EnsureChildControls ();
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
Something like that should work for you...

Resources