I'm new to C# asp.net and I'm having trouble getting the selected item. Here is the code behind:
List<string> figuritasSelecionadas = new List<string>();
this.lblMensaje.Visible = false;
decimal total = 0;
foreach (ListItem lf in this.ListaFiguritas.Items)
{
if (lf.Selected)
{
figuritasSelecionadas.Add(lf.Text);
total += Decimal.Parse(lf.Value);
}
}
The problem here is that it doesn't matter which item is selected, because when it reaches the if the first item is marked as true. And I have no idea why it's doing this.
Here is how I load the ListBox:
private void cargarFiguritas()
{
List<Figurita> figuritas = Sistema.Instancia.figuritasQueFaltan(usuarioActivo);
this.ListaFiguritas.DataSource = figuritas;
this.ListaFiguritas.DataValueField = "Precio";
this.ListaFiguritas.DataTextField = "NumeroFigurita";
this.ListaFiguritas.DataBind();
Session["ListaFiguritas"] = figuritas;
}
protected void Page_Load(object sender, EventArgs e)
{
usuarioActivo = (string)Session["nombreUsuario"];
this.lblUsuario.Text = (string)Session["nombreUsuario"] + " tiene un total de: " + Session["Monedas"].ToString() + " monedas";
if (!IsPostBack)
{
cargarFiguritas();
}
}
Here is the aspx code:
<asp:ListBox ID="ListaFiguritas" runat="server" Height="180px" Width="110px" SelectionMode="Single">
</asp:ListBox>
Related
I select one value on the ddl , and it does not show the products in the page. The selected value remains binded but the page is blank.
Also , if I just call function getCat() without using if(!ispostback). When i load the page the drop down list is stuck on the first value , but it shows the products in page.
Drop Down List:
<asp:dropdownlist runat="server" id="ddcateg" AutoPostBack="true" onselectedindexchanged="Ddcateg_SelectedIndexChanged"></asp:dropdownlist>
This is the implementation:
protected void Page_Load(object sender, EventArgs e)
{
//afisare();
if (!IsPostBack)
{
getCateg();
}
}
public void getCateg()
{
ProdusTipModel model = new ProdusTipModel();
FarmacieEntities db = new FarmacieEntities();
var lizt = (from c in db.ProdusTips select c).ToList();
ddcateg.DataSource = lizt;
ddcateg.DataValueField = "ID";
ddcateg.DataTextField = "Name";
ddcateg.DataBind();
ddcateg.SelectedIndexChanged += Ddcateg_SelectedIndexChanged;
}
public void afisare2(List<Produ> z)
{
ProdusModel mdl = new ProdusModel();
foreach (var produs in z)
{
Panel produsePnl = new Panel();
ImageButton imageButton = new ImageButton();
produsePnl.BorderColor = Color.AliceBlue;
Label lblNume = new Label();
Label lblPret = new Label();
produsePnl.BorderStyle = BorderStyle.Groove;
produsePnl.BorderColor = Color.LightSkyBlue;
imageButton.ImageUrl = "~/Img/Produse/" + produs.Image;
imageButton.CssClass = "imgProdus";
imageButton.PostBackUrl = "~/Pages/PaginaProdus.aspx?id=" + produs.ID;
lblNume.Text = produs.Name;
lblNume.CssClass = "numeProd";
lblPret.Text = produs.Price + "lei";
lblPret.CssClass = "produsPret";
produsePnl.Controls.Add(imageButton);
produsePnl.Controls.Add(new Literal { Text = "<br /" });
produsePnl.Controls.Add(lblNume);
produsePnl.Controls.Add(new Literal { Text = "<br /" });
produsePnl.Controls.Add(lblPret);
pnlProduse.Controls.Add(produsePnl);
}
}
private void Ddcateg_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList selectedList = (DropDownList)sender;
int selectedLit = Convert.ToInt32(selectedList.SelectedValue);
ProdusModel mdl = new ProdusModel();
List<Produ> list = mdl.GetProdCateg(selectedLit).ToList();
afisare2(list);
}
Your problem could be that your code behind method is private:
private void Ddcateg_SelectedIndexChanged(object sender, EventArgs e)
Try making it protected or public so it can be seen by the aspx page.
First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}
I have populated my checkboxlist on the fly via callback like this:
<dx:ASPxComboBox ID="ASPxComboBox_Prot" runat="server" DataSourceID="SqlDataSource_Prot"
TextField="LIBELLE" ValueField="NO_PROT" ValueType="System.Int32">
<ClientSideEvents SelectedIndexChanged="function(s, e) { cbp_ProtOrdos.PerformCallback(s.GetValue());}" />
</dx:ASPxComboBox>
</td>
</tr>
</table>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel_ProtOrdo" runat="server"
ClientInstanceName="cbp_ProtOrdos" OnCallback="cbp_ProtOrdo_Callback">
<PanelCollection>
<dx:PanelContent>
<dx:ASPxCheckBoxList ID="CheckBoxList_Ordo" runat="server" ClientInstanceName="CheckBoxList_Ordo" ValueType="System.Int32" TextField="LIBELLE" ValueField="NO_ORDO">
</dx:ASPxCheckBoxList>
<dx:ASPxButton ID="ASPxButton_ProtOrdoGen" runat="server"
Text="Générer ordonnance & Planifier pour infirmier"
OnClick="ASPxButton_ProtOrdoGen_Click"
EnableDefaultAppearance="false" BackColor="Yellow" CssClass="bt" Theme="BlackGlass" ForeColor="Black">
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And on server side code:
protected void cbp_ProtOrdo_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
var panel = sender as ASPxCallbackPanel;
var cblist = panel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
cblist.DataSource = Outils.Get_ProtOrdo(ASPxComboBox_Prot.Value.ToString());
cblist.DataBind();
}
It works fine, but now I want to get the value that had been checked by the user. So I add the button to do that.
protected void ASPxButton_ProtOrdoGen_Click(object sender, EventArgs e)
{
//TabPage oPage = ASPxPageControl_DosSoin.TabPages.FindByName("Surveillance");
//ASPxPanel oPanel = (ASPxPanel)oPage.FindControl("ASPxPanel_ListSurveil");
//ASPxRoundPanel oRoundPnl = (ASPxRoundPanel)oPanel.FindControl("ASPxRoundPanel_ProtOrdo");
//ASPxCallbackPanel ocbpPanel = (ASPxCallbackPanel)oRoundPnl.FindControl("ASPxCallbackPanel_ProtOrdo");
//ASPxCheckBoxList cblist = (ASPxCheckBoxList)ocbpPanel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
List<string> selectItems_Ordo = new List<string>();
foreach (var oItem in CheckBoxList_Ordo.Items)
{
ListEditItem oNewChk = (ListEditItem)oItem;
if (oNewChk.Selected)
{
selectItems_Ordo.Add( oNewChk.Value.ToString());
}
}
foreach (var oItem in selectItems_Ordo)
{
if (DossierDuSoins.check_doublon_ordo(oItem.ToString(), Soin_Id) == 0)
DossierDuSoins.RamenerVal(DossierDuSoins.GetLibOrdo(oItem.ToString()), Soin_Id, oItem.ToString());
}
string TempId = "";
if (selectItems_Ordo.Count == 0)
{
lbl_err.Text = "Pas de médicament de sélectionné";
}
else
{
foreach (string selectItemId in selectItems_Ordo)
{
if (TempId != "")
TempId += ",";
TempId += selectItemId.ToString();
}
string AdrUrl = "Print_Ordo.aspx?SoinId=" + Soin_Id + "&SelId=" + TempId;
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
}
}
The problem is that I can not get my checked value. Is that because the postback destroys all checkboxlists that I had constructed on the fly ?
Try this instead of using vars for selecting your checkbox list
foreach (ListItem yourItem in YourCheckBoxList.Items)
{
if (item.Selected)
{
// If the item is selected, Add to your list/ save to DB
}
else
{
// If item is not selected, do something else.
}
}
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
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();
}
}