Hi Stackoverflow community!
I'm working on a Sharepoint 2013 Server with Visual Studio 2012 and Windows Server 2012. So, I have to build a Webpart which should add a link via textbox to the GUI. Furthermore, it should be possible to add another link as well. After adding a new link, the whole collection of links should be displayed in a list. The problem is now: after adding a link, the site reloads. As a consequence the array, which stores the links, does only contain the latest link. All previous links are gone/deleted.
Here's my approach on this:
protected void Page_Load(object sender, EventArgs e) {
if (Page.IsPostBack) {
Events = new List<String>();
}
}
protected void btnAddLink_click(object sender, EventArgs e) {
AddToList();
List<String> links = Events;
foreach (String s in links) {
HyperLink link = new HyperLink();
link.NavigateUrl = s;
link.Text = s;
lnkPanel.Controls.Add(link);
}
foreach (String l in links) {
tbDescription.Text += l + "\n";
}
}
public List<String> Events {
get { return (List<String>)ViewState["HyperLinkList"]; }
set { ViewState["HyperLinkList"] = value; }
}
public void AddToList() {
List<String> events = Events; // Get it out of the viewstate
String l = tbLinks.Text; // tb = textbox (user input)
HyperLink link = new HyperLink();
link.NavigateUrl = tbLinks.Text;
link.Text = tbLinks.Text;
if (!events.Contains(link.NavigateUrl.ToString())) {
events.Add(l);
}
Events = events; // Add the updated list back into the viewstate
}
I hope someone can help me with my (maybe nooby) problem.
Ahhh you need this:
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
Events = new List<String>();
}
}
Each time the page is loaded, your wiping the contents of the list in viewstate. You need to add the ! to make sure it's not a postback.
Related
Whenever DropDownList SelectedIndexChanged, I am adding LinkButtons as ul-li list in codebehind. Each linkbuttons were assigned with IDs and a common Click event. Problem is code in Click event is not executed or maybe event is not triggered. My code below: [Edit] I tried like this as suggested in other posts (dynamically created list of link buttons, link buttons not posting back)
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
private void Clicked(object sender, EventArgs e)
{
var btn = (LinkButton)sender;
label1.Text = btn.ID.ToString();
}
Im missing something. Any help please.
Here the issue is with the ViewState. When the selected index of the dropdownlist changes there is a postback which takes place and the previous state is lost, so at this point you have to maintain the state of the controls.
Now in your code actually the state of the control is lost and so the click event does not fire. So the solution is to maintain the state of the controls.
The Below is a working example, you can just paste it and try.
This is my page load.
protected void Page_Load(object sender, EventArgs e)
{
for (var i = 0; i < LinkButtonNumber; i++)
AddLinkButton(i);
}
Similarly you have to maintain the state of the previously added control like this.
private int LinkButtonNumber
{
get
{
var number = ViewState["linkButtonNumber"];
return (number == null) ? 0 : (int)number;
}
set
{
ViewState["linkButtonNumber"] = value;
}
}
The below is my SelectedIndexChanged Event for the DropDownList
protected void Example_SelectedIndexChanged(object sender, EventArgs e)
{
AddLinkButton(LinkButtonNumber);
LinkButtonNumber++;
}
I have a function which dynamically creates the controls, which is called on the page load and on SelectedIndexChanged.
private void AddLinkButton(int index)
{
LinkButton linkbutton = new LinkButton { ID = string.Concat("txtDomain", index) };
linkbutton.ClientIDMode = ClientIDMode.Static;
linkbutton.Text = "Link Button ";
linkbutton.Click += linkbutton_Click;
PanelDomain.Controls.Add(linkbutton);
PanelDomain.Controls.Add(new LiteralControl("<br />"));
}
And this is the Click event for the LinkButton
void linkbutton_Click(object sender, EventArgs e)
{
//You logic here
}
I solved it using brute code lol.
Since controls' event were not bound on postback then we recreate them on postback. So in my Page_Load I called the module that re-creates the controls, thus binding them to corresponding event. This works, but...
Re-creating these controls create duplicates (Multiple Controls with same ID were found) and you will get into trouble in instances of finding a control by ID like using panel.FindControl.
To remedy this scenario, I put a check if same control ID already existed before recreating them, and voila! It works.
protected void Page_Load(object sender, EventArgs e)
{
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
if (liList.FindControl(dr["col1"].ToString()) == null)
{
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
}
I'm trying to get checkbox list values to a single string. in ASP.net using C#.
Here's my code.. I have declared this globally.
string hobbies = "";
This is the code to get the selected items to a string.
protected void chkListHobbies_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
I'm displaying this on button click
protected void btnEnter_Click(object sender, EventArgs e)
{
Response.Write("Hobbies= "+hobbies);
}
It doesn't give the expected output.
Would like to get this corrected if it's wrong or would like to know how to do it properly.
Thanks in advance.
You have to create hobbies list in your btnEnter_Click event handler because Asp.net webforms in stateless and you'll get a new hobbies variable after each postback. To address this issue you have to save hobbies state somehow (using viewstate or a hidden field) and use it later or as I suggested create hobbies list in btnEnter_Click.
Edit (examples):
1.Do the whole thing in btnEnter_Click:
protected void btnEnter_Click(object sender, EventArgs e)
{
string hobbies = "";
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
Response.Write("Hobbies=" + hobbies);
2.Use ViewState:
private string hobbies
{
get { return (ViewState["hobbies"] ?? "").ToString(); }
set { ViewState["hobbies"] = value; }
}
and the rest of your code is exactly the same.
hi guy i am trying to place my session in to a drop down, any help would be great.
at the moment it puts the data in to a label, i wish to put it into a dropdown with it adding a new string every time i click button without getting rid of the last
default page
protected void Button1_Click1(object sender, EventArgs e)
{
Session["Fruitname"] = TbxName.Text; // my session i have made
}
output page
protected void Page_Load(object sender, EventArgs e)
{
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = fruitname; // session used in lable
}
Have Tried
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(listbox1.Text);
but i get error when i try to run the program
Broken glass thanks for your help, it is still not doing what i need but its getting there.
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = string.Join(",", fruitname); // session used in lable
this is what is working. i need a dropdown to display all the strings put into TbxName.Text; to output into fruit
Just use a List<string> instead of a string then.
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(TbxName.Text);
Has been fixed using code found else where
button page code bellow
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
{
public List<string> MyFruit { get; set; }
}
page where display
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
ListBox1.DataSource = MyFruit;
ListBox1.DataBind();
}
public List<string> MyFruit { get; set; }
}
I need help to get a response when I click on an "Item" from a list view. Know that there is selectedindexchanged, but when I try to display a MessageBox so nothing happens, have tried lots of other things but have not managed to come up with something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
while (reader.Read())
{
string alio = reader["fornamn"].ToString();
string efternamn = reader["efternamn"].ToString();
ListViewItem lvi = new ListViewItem(alio);
listView1.Items.Add(lvi);
lvi.SubItems.Add(efternamn);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Assuming that 81.private void listView1_SelectedIndexChanged is properly linked to the listview, you will need to query the listview to find out what's selected:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.listView1.SelectedItems.Count == 0)
return;
string namn = this.listView1.SelectedItems[0].Text;
// Create the sql statement to retrieve details for the user
string sql = string.Format("select * from kunder where fornamn = '{0}', namn);
// do the same as you do to create a reader and update the controls.
}
Going by the term "when I try to display a MessageBox so nothing happens"\, I assume that you simply put MessageBox.Show("blah"); inside the event handler and never got it shown.
If that's the case, your event handler is not hooked properly to your form's list view. go back and see the text listView1_SelectedIndexChanged is anywhere to be found inside your Form1.Designer.cs file.
If not (or anyway), start over on a new form. That's the easiest way out. :)
private void lstView_KQ_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstView_KQ.SelectedItems.Count > 0)
{
ListViewItem itiem = stView_KQ.SelectedItems[lstView_KQ.SelectedItems.Count - 1];
if (itiem != null)
foreach (ListViewItem lv in lstView_KQ.SelectedItems)
{
txtMaNV.Text = lv.SubItems[0].Text;
cmbCV.Text = lv.SubItems[1].Text;
txtHoNV.Text = lv.SubItems[2].Text;
txtTenNV.Text = lv.SubItems[3].Text;
txtNgaysinh.Text = lv.SubItems[4].Text;
txtGioiTinh.Text = lv.SubItems[5].Text;
txtDiaChi.Text = lv.SubItems[6].Text;
txtSDT.Text = lv.SubItems[7].Text;
txtCMND.Text = lv.SubItems[8].Text;
}
}
}
I have a web part for managing comments related to ongoing promotions. The web part is hosted in a Sandbox Solution because server access of all kinds is restricted (//sharepoint)
I have two main issues with my code.
1: Items submitted do not appear after postback, leaving user to think their comments was not saved,
2: PostBack data refires after page refresh, meaning if a user refreshes hoping to see their comments, it is re-submitted and saved.
What am I doing wrong here?
public string OfferID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
protected void LoadOffers()
{
if (!String.IsNullOrEmpty(OfferID))
{
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
else
{
OfferID = "123";
PopulateOfferDetails(OfferID);
PopulateComments(OfferID);
PopulateBestPractices(OfferID);
}
}
protected void PopulateComments(string offerID)
{
rcOiD.InnerText += " " + offerID;
List<Comment> Comments = new List<Comment>();
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPQuery query = new SPQuery();
query.RowLimit = 100;
query.Query = "<Where><Eq><FieldRef Name=\"OfferID\"/><Value Type=\"Text\">" + offerID + "</Value></Eq></Where>";
try
{
SPListItemCollection items = TargetList.GetItems(query);
if (items.Count > 0)
{
commentsCount.InnerText = items.Count.ToString();
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
string profilePicBase = "<div class=\"profilePic\" " + "style=\"background-image:url('http://who/Photos/XX.jpg');\"" + "> </div>";
foreach (SPListItem item in items)
{
Comment c = new Comment();
c.Author = ((string)item["Created By"]).CleanUserName();
c.Body = (string)item["Body"];
c.Date = String.Format("{0:MMM dd, yyyy}", (DateTime)item["Created"]);
c.ProfilePic = profilePicBase.Replace("XX", alias);
Comments.Add(c);
}
Comments.Reverse();
CommentRepeater.DataSource = Comments;
CommentRepeater.DataBind();
}
else
{
commentsCount.InnerText = "0";
}
}
catch (Exception ex)
{
}
}
protected void SubmitListItem(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
SPUser user = web.CurrentUser;
string alias = user.Email.Substring(0, user.Email.IndexOf('#'));
if (ListChoice.SelectedItem.Text == "comment")
{
SPList TargetList = web.Lists.TryGetList("Offer Comments");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item["Alias"] = alias;
item.SystemUpdate();
TargetList.Update();
}
else
{
SPList TargetList = web.Lists.TryGetList("Offer Best Practices");
SPListItem item = TargetList.Items.Add();
item["Title"] = TitleBox.Text;
item["Body"] = BodyBox.Text;
item["OfferID"] = OfferID;
item.SystemUpdate();
TargetList.Update();
}
}
}
EDIT: I can confirm this isn't a databind() issue. The item.count being pulled on postback is being rendered properly, but is still 1 item short.
I assume SubmitListItem is an event handler of an control on the page.
If that is so then as in your previous question, Page_Load is is fired before any control's event handler.
Therefore on postback your repeater is getting bound before the item addition occurs so on that load you do not get to see the new item.
To prevent this rebind the repeater after item addition.
I think you should do this only if not is page postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
OfferID = Context.Request.QueryString["ItemID"];
LoadOffers();
}
}