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.
Related
Hi i am creating dropdownlist dynamically but on post back it is loosing the value and i am unable to get values on button click event.
private void CreateDropdownListEmployee(string id,Panel pnl, DataTable dt)
{
DropDownList drp = new DropDownList();
drp.ID = id;
drp.CssClass = "activeuserTxt";
drp.ClientIDMode = ClientIDMode.Static;
drp.DataSource = dt;
drp.DataTextField = "name";
drp.DataValueField = "id";
drp.DataBind();
pnl.Controls.Add(drp);
}
For the dynamic texbox i am using the below code on PAge_Init
protected void Page_Init(object sender, EventArgs e)
{
try
{
int SNID = 0;
List<string> keysNetmr = Request.Form.AllKeys.Where(key => key.Contains("txt")).ToList();
foreach (string key in keysNetmr)
{
this.CreateTextBox("txtNermr" + SNID, 100, pnlSN);
SNID++;
}
}
catch (Exception ex) { }
}
private void CreateTextBox(string id, int width, Panel pnl)
{
TextBox txt = new TextBox();
txt.ID = id;
txt.Width = width;
txt.Attributes.Add("autocomplete", "off");
txt.CssClass = "activeuserTxt";
pnl.Controls.Add(txt);
}
Can anyone help me on this.
here is my code
after button 2 click event it is creating the dropdown in table rows but when I try to save by button 1 click event it just disappear. I have not find any solution regarding this. I have used find control view State etc but it's not helping.
I want to store selected values of dropdown after button_1 click event starts.
public partial class StudentClassSectionMapping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClassCode.Enabled = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
UpdateModalShowFlag.Value = "true";
Check.Value = "true";
CreateTableRows();
}
private void CreateTableRows()
{
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
ClassMaster.ClassMasterForm classCode = Schoolclasses.GetInfo(h);
ClassCode.Text = classCode.cCode;
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allSectionsInClass = StudentsClassSectionMapping.GetSectionsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
DropDownList t = new DropDownList();
t.Items.Add("No Section");
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm sectionList in allSectionsInClass)
{
t.Items.Add(sectionList.ssSection);
t.Items[t.Items.Count - 1].Value = sectionList.ssSectionID.ToString();
}
t.Attributes.Add("class", "form-control");
t.ID = studentList.ssStudentId.ToString();
cell1.Text = studentList.ssName;
cell2.Text = studentList.ssRegistrationNumber;
cell3.Controls.Add(t);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
Table1.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTableRows();
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
DropDownList d = Table1.FindControl(studentList.ssStudentId.ToString()) as DropDownList;
if (d != null)
{
if (d.SelectedIndex != 0)
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = studentList.ssStudentId;
studentSectionMapping.ssStudentId = long.Parse(d.SelectedItem.Value);
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
else
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = 0;
studentSectionMapping.ssStudentId = 0;
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
}
}
}
It get vanished/disappear because you added it dynamically on page. If you want it back or want to reserver control which is dynamically created you need to recreate again and need to add dynamically.
Here is good example of how you can do it : How to create controls dynamically in ASP.NET and retrieve values from it
I am grabbing some records from a database depending on the id number of the page, the amount of records that will display will vary, anywhere to 1 record to 50. I need to take these records then choose which ones I will be modifying, deleting, or won't change at all. I would like it to look like this:
Can't get image to show with stackoverflow image uploader so here: https://dl.dropboxusercontent.com/u/9446763/code/dropdownlist.jpg
I would like the text fields to be disabled if No Change or Remove is selected, and the fields enabled for revising if the option Modify is selected.
Below is what I have so far, the part I am struggling on is the selectedindex change I do not know how to code it so that when Modify is selected in the dropdown box the appropriate textboxes become enabled.
ASPX Page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
CS Page
private void createControls()
{
var id = Request.Params["ID"];
System.Data.OleDb.OleDbConnection pcn;
System.Data.OleDb.OleDbCommand pcm;
System.Data.OleDb.OleDbDataReader prs;
pcn = new System.Data.OleDb.OleDbConnection("");
pcm = new System.Data.OleDb.OleDbCommand();
pcn.Open();
pcm.Connection = pcn;
var tableSql = #"select * FROM grouplist where ptid = '" + id + "'";
pcm.CommandText = tableSql;
prs = pcm.ExecuteReader();
var rowcount = 0;
while (prs.Read())
{
rowcount++;
PlaceHolder1.Controls.Add(new Literal() { Text = "<div class='row'><div class='span3'>" });
TextBox tx = new TextBox();
tx.ID = "txtData" + rowcount.ToString();
tx.Text = prs["name"].ToString().Trim();
tx.Width = 200;
tx.CssClass = "span2";
tx.Enabled = false;
PlaceHolder1.Controls.Add(tx);
PlaceHolder1.Controls.Add(new Literal() { Text = "</div><div class='span2'>" });
TextBox txa = new TextBox();
txa.ID = "amtData" + rowcount.ToString();
txa.Text = prs["amt"].ToString();
txa.CssClass = "span2";
txa.Enabled = false;
PlaceHolder1.Controls.Add(txa);
PlaceHolder1.Controls.Add(new Literal() { Text = "</div><div class='span3'>" });
DropDownList ddl = new DropDownList();
ddl.Items.Add("No Change");
ddl.Items.Add("Modify");
ddl.Items.Add("Remove");
ddl.Width = 200;
ddl.CssClass = "span2";
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
ddl.AutoPostBack = true;
ddl.ID = "ddlData" + rowcount.ToString();
PlaceHolder1.Controls.Add(ddl);
PlaceHolder1.Controls.Add(new Literal() { Text = "</div></div>" });
}
prs.Close();
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
}
You need to have members in your class that hold references to your DropDownList and other controls that you want to enable/disable.
public class YourClass {
private DropDownList ddl;
private TestBox txa;
private void createControls {
// ...
TextBox txa = new TextBox();
txa.ID = "amtData" + rowcount.ToString();
// ...
DropDownList ddl = new DropDownList();
ddl.Items.Add("No Change");
// ... etc.
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddl.SelectedIndex == 1)
txa.Enabled = true;
}
}
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 an AJAX accordion from the ajax control toolkit on a page with a datagrid inside on of the panels. I have a custom itemtemplate for the one column to create a multiline textbox when I click edit on the row. When I click update on the row, the original content of the textbox gets rendered into the textbox. It is supposed to update and go back to the literal not the textbox. When I put the DataBind() into a !IsPostBack, it doesnt get rendered when I click on the accordion pane. Any ideas?
Code:
protected void Page_Load(object sender, EventArgs e)
{
announ.HeaderStyle.CssClass = "header";
announ.Width = Unit.Percentage(100);
announ.GridLines = GridLines.None;
announ.AutoGenerateColumns = false;
announ.CellPadding = 10;
announ.CellSpacing = 0;
announ.HorizontalAlign = HorizontalAlign.Center;
announ.HeaderStyle.Font.Bold = true;
announ.EnableViewState = false;
announ.AlternatingItemStyle.BackColor = System.Drawing.Color.GhostWhite;
//announ.DeleteCommand += AnnounDeleteCommand;
announ.EditCommand += announ_EditCommand;
announ.UpdateCommand += announ_UpdateCommand;
announ.CancelCommand += announ_CancelCommand;
announ.DataKeyField = "id";
var tc1 = new TemplateColumn
{
HeaderTemplate = new
DataGridTemplate(ListItemType.Header, "Announcement"),
ItemTemplate = new DataGridTemplate(ListItemType.Item, "announcement_text"),
EditItemTemplate = new
DataGridTemplate(ListItemType.EditItem, "announcement_text")
};
var editColumn = new EditCommandColumn
{
ButtonType = ButtonColumnType.PushButton,
HeaderText = "Edit",
EditText = "Edit",
UpdateText = "Update",
CancelText = "Cancel"
};
var dateColumn = new BoundColumn {HeaderText = "Posted On", DataField = "date", ReadOnly = true};
var expirationColumn = new BoundColumn {HeaderText = "Expiration Date", DataField = "expiration_date"};
announ.Columns.Add(tc1);
announ.Columns.Add(dateColumn);
announ.Columns.Add(expirationColumn);
announ.DataSource = myAnnouncements;
announ.DataBind();
var deptMgtaccord = new Accordion
{
ID = "deptMgtaccord",
HeaderCssClass = "accordion-header",
HeaderSelectedCssClass = "accordion-headerSelected",
AutoSize = AutoSize.None,
SelectedIndex = 0,
FadeTransitions = true,
TransitionDuration = 250,
FramesPerSecond = 40,
RequireOpenedPane = false,
SuppressHeaderPostbacks = true
};
if (IsPostBack)
{
deptMgtaccord.SelectedIndex = selected;
}
var announcementPane = new AccordionPane {ID = "announcementPane"};
announcementPane.HeaderContainer.Attributes.Add("onmouseover", "this.style.backgroundColor='#e3e2e2';");
announcementPane.HeaderContainer.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
announcementPane.HeaderContainer.Controls.Add(new LiteralControl("Announcements >>"));
announcementPane.ContentContainer.Controls.Add(announ);
deptMgtaccord.Panes.Add(announcementPane);
var statsPane = new AccordionPane {ID = "statsPane"};
statsPane.HeaderContainer.Attributes.Add("onmouseover", "this.style.backgroundColor='#e3e2e2';");
statsPane.HeaderContainer.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff';");
statsPane.HeaderContainer.Controls.Add(new LiteralControl("Statistics >>"));
statsPane.ContentContainer.Controls.Add(new LiteralControl("Stats"));
deptMgtaccord.Panes.Add(statsPane);
ph1.Controls.Add(deptMgtaccord);
}
protected void announ_CancelCommand(object source, DataGridCommandEventArgs e)
{
announ.EditItemIndex = -1;
announ.DataBind();
}
protected void announ_UpdateCommand(object source, DataGridCommandEventArgs e)
{
var dc = new MTCDataDataContext();
var announText = (TextBox) e.Item.Cells[1].Controls[1];
int announId = (int)announ.DataKeys[e.Item.ItemIndex];
var currentAnnoun = (from a in dc.announcements
where a.id == announId
select a).SingleOrDefault();
currentAnnoun.announcement_text = announText.Text;
dc.SubmitChanges();
announ.EditItemIndex = -1;
announ.DataBind();
}
protected void announ_EditCommand(object source, DataGridCommandEventArgs e)
{
announ.EditItemIndex = e.Item.ItemIndex;
announ.DataBind();
}
public class DataGridTemplate : ITemplate
{
ListItemType templateType;
string columnName;
public DataGridTemplate(ListItemType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(Control container)
{
Literal lc = new Literal();
TextBox tb = new TextBox();
switch (templateType)
{
case ListItemType.Header:
lc.Text = "<B>" + columnName + "</B>";
container.Controls.Add(lc);
break;
case ListItemType.Item:
lc.DataBinding += lc_DataBinding;
container.Controls.Add(lc);
break;
case ListItemType.EditItem:
tb.TextMode = TextBoxMode.MultiLine;
tb.Rows = 6;
tb.Columns = 57;
tb.DataBinding += tb_DataBinding;
container.Controls.Add(tb);
break;
case ListItemType.Footer:
lc.Text = "<I>" + columnName + "</I>";
container.Controls.Add(lc);
break;
}
}
void tb_DataBinding(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
DataGridItem row = (DataGridItem)tb.NamingContainer;
tb.ID = "txt_" + row.ItemIndex;
tb.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}
void lc_DataBinding(object sender, EventArgs e)
{
Literal lc = (Literal)sender;
DataGridItem row = (DataGridItem)lc.NamingContainer;
lc.ID = "txt_" + row.ItemIndex;
lc.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}
}
You need to add your dynamic controls in PreInit on every request in order for the controls to get back into the ControlTree and raise events.
Page Event:
PreInit
Typical Use:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first
time the page is being processed. The
IsCallback and IsCrossPagePostBack
properties have also been set at this
time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Note: If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.