ASP.NET Textbox text does not change while trying to update - c#

I have a form where there is a ListBox, a textbox and four buttons called Save, Edit, Delete and Clear. I'm retrieving data from database and populating the ListBox. When I select one of the items in the ListBox, it is populated into the textbox. Now when I delete that item, there is nothing wrong, it works fine. But when I try to update that item, i.e. change the text in the textbox and then click the Edit button, there is problem. In the textbox, I can see the text is being changed, no problem with that, but when I debugged, I found in the backend, the textbox is still containing the old text and not the modified one.
What am I doing wrong?
Here's my UI code:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<h1>Employee Category</h1>
<table>
<td>
<asp:ListBox ID="listEmployeeCategory" runat="server" Height="164px" Width="210px" AutoPostBack="true" />
</td>
<td>
<table>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" Text="" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmpCategoryName" runat="server" Text="Name: " Font-Bold="true" />
</td>
<td>
<asp:TextBox ID="txtEmpCategoryName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="rqdEmpCategoryName" ControlToValidate="txtEmpCategoryName" ErrorMessage="Employee Category Name can't be empty!" Style="color:Red" runat="server" />
</td>
</tr>
</table>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClick="btnDelete_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" />
</td>
</table>
</asp:Content>
And here's my backend code, for the sake of everyone's understanding, I'm posting my entire backend code (except the BL, DAL and DAO codes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Shelter.DAO.MasterEntry;
using Shelter.BLL.MasterEntry;
namespace Shelter.UI.MasterEntry
{
public partial class EmployeeCategoryUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListBox();
}
else
{
if (listEmployeeCategory.SelectedIndex != -1)
{
LoadDataIntoTextBox(Convert.ToInt32(listEmployeeCategory.SelectedValue));
}
}
}
private void LoadDataIntoTextBox(int val)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(val);
DataTable EmpCategoryDt = new DataTable();
EmpCategoryDt = empCategoryBLL.RetrieveById(objEmployeeCategory);
txtEmpCategoryName.Text = EmpCategoryDt.Rows[0]["EmpCategoryName"].ToString();
}
private void LoadDataIntoListBox()
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
DataSet EmployeeCategoryDs = new DataSet();
EmployeeCategoryDs = empCategoryBLL.RetreiveFromTable();
DataTable EmployeeCategoryDt = EmployeeCategoryDs.Tables[0];
DataRow tempRow = null;
foreach (DataRow tempRow_Variable in EmployeeCategoryDt.Rows)
{
tempRow = tempRow_Variable;
string rowText = tempRow["EmpCategoryName"] + "(" + tempRow["ID"] + ")";
string rowValue = tempRow["ID"].ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
bool isSave = empCategoryBLL.SaveToTable(objEmployeeCategory);
if (isSave)
{
int id = empCategoryBLL.ReturnLastInsertedId();
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data saved successfully!";
string rowText = txtEmpCategoryName.Text + "(" +id.ToString()+ ")" ;
string rowValue = id.ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data saving failed!";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isEdit = empCategoryBLL.EditInTable(objEmployeeCategory);
if (isEdit)
{
int id = objEmployeeCategory.ID;
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isDelete = empCategoryBLL.DeleteFromTable(objEmployeeCategory);
if (isDelete)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data deleted successfully!";
listEmployeeCategory.Items.Remove(new ListItem(listEmployeeCategory.SelectedItem.Text, listEmployeeCategory.SelectedValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data deleting failed!";
}
}
}
}
}
The txtEmpCategoryName.Text is still containing the old value, so whenever I try to update, it only takes the old value and not the modified value in the textbox. It seems that the TextChanged event is not working. What is the fix to this problem?

You can use Entity frame in Visual studio;
right click on your solution - select new Add - then New Project - C# -Class Library give it a project name and Click Ok to add a new project to your existing project.
rename your class to a meaning name such as BusinessLogic and make it public.
right click on the newly added project and select add new item, on your popup windows select data on the right panel then select ADO.NET Entity Data Model rename your edmx to a meaningful name and click on add. default option and click on next, point to your SQL database by clicking on the new Connection.
select your store procedure for populating your listbox and updating the description and click on Finish.
CREATE PROCEDURE Proc_name AS BEGIN SET NOCOUNT ON;
SELECT ID,Description FROM Table_Name END
CREATE PROCEDURE [dbo].[UpdateEmpCategoryBLL]
#ID int, #Description varchar(50) AS BEGIN
SET NOCOUNT ON;
UPDATE Question1 SET Description = #Description WHERE ID = #ID
END
In your class Implement your methods for populating listbox and updating the description
public class Wrapper
{
public static List EmployeeCategory()
{
try
{
return new LOOKUPEntities().empCategoryBLL().ToList();
}
catch (Exception)
{
throw;
}
}
public static void UpdateEmpCategory(int id, string description)
{
try
{
using (LOOKUPEntities client = new LOOKUPEntities())
{
client.UpdateEmpCategoryBLL(id, description);
}
}
catch (Exception)
{
throw;
}
}
}
copy the connection string from you app.config to your web.config. Then add your class library to your references by right clicking on your references and select add reference, select solution and click on add. Add also System.Data,Entity and click ok.
now;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
protected void BindListBox()
{
try
{
ListItem lstBox;
listEmployeeCategory.Items.Clear();
var query = Wrapper.EmployeeCategory();
foreach (var items in query)
{
lstBox = new ListItem(items.Description, items.ID.ToString());
listEmployeeCategory.Items.Add(lstBox);
}
}
catch(Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data loading failed "+ ex +" !";
}
}
protected void listEmployeeCategory_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = false;
try
{
Session["ID"] = listEmployeeCategory.SelectedValue.ToString();
txtEmpCategoryName.Text = listEmployeeCategory.SelectedItem.ToString();
}
catch (Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Loading session data failed " + ex + " !";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(Session["ID"].ToString());
Wrapper.UpdateEmpCategory(id, txtEmpCategoryName.Text.Trim());
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
BindListBox();
txtEmpCategoryName.Text = string.Empty;
}
catch
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
done!

Related

Alternate visibility for 2 tables

I am having this kind of structure in a Web Application where depending on the user's choices Table_1 or Table_2 is given visibility; they never can be both visible.
<table>
<tr><td>
<table id="Table_1" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
<asp:Linkbutton>
<asp:FormView>
</td></tr>
</table>
<table id="Table_2" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
</td></tr>
</table>
</td></tr>
</table>
The strange thing is that this works only if the hole code block for table 2 is on top. If I switch them back to the way described by the code, table_2 never will show up. I do not add anything more. Just by switching the two tables in the code, once the result is correct, while in the other case it isn't.
What can this be related to?
Martin
Code that controls visibility:
protected void GridView01_OnSelectedIndexChanged(object sender, EventArgs e)
{
FilterDDLResponsable.SelectedIndex = -1;
GridView3.Visible = true;
GridView3.EditIndex = -1;
Table_1.Visible = true;
Table_2.Visible = false;
GridView3.DataBind();
ButtonEditMode.Visible = false;
ButtonSendHWReminderSeries.Visible = false;
if (AdminUser.Text == "1")
{
AddButton.Visible = true;
}
LabelAuditID.Text = Convert.ToString(GridView01.SelectedValue);
if(ActivateTabletView.Checked == true)
{
GridView01.Columns[12].Visible = true;
GridView01.Columns[13].Visible = true;
GridView01.Columns[14].Visible = true;
}
else
{
GridView01.Columns[12].Visible = false;
GridView01.Columns[13].Visible = false;
GridView01.Columns[14].Visible = false;
}
FillGrid();
}
and the Grid's row LinkButton onClick method:
protected void OpenAudit(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string AuditID = btn.CommandArgument;
Table_1.Visible = false;
Table_2.Visible = true;
LabelAuditID.Text = AuditID;
foreach (GridViewRow gvRow in GridView01.Rows)
{
if ((int)GridView01.DataKeys[gvRow.DataItemIndex].Value == Convert.ToUInt32(AuditID))
{
GridView01.SelectedIndex = gvRow.DataItemIndex;
break;
}
}
FillQuestionsGrid();
}

stop postback on treeview node click

I followed this tutorial to allow a user to select a folder from their machine:
http://www.codeproject.com/Articles/21895/Directory-Browsing-in-ASP-Net
The problem is that every time I click on a node, it calls postback, which refreshes the page. So how do I stop postback being called every time?
<asp:TreeView ID="TreeView1" runat="server" Height="326px" ImageSet="XPFileExplorer"
NodeIndent="15" Width="292px">
<ParentNodeStyle Font-Bold="False" />
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px" />
<LeafNodeStyle ImageUrl="../images/folder.gif" />
</asp:TreeView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TreeNode onjParent = new TreeNode("C:\\", "C:\\");
onjParent.PopulateOnDemand = true;
TreeView1.Nodes.Add(onjParent);
TreeView1.CollapseAll();
}
error.Visible = false;
TreeView1.TreeNodeExpanded += new TreeNodeEventHandler(TreeView1_TreeNodeExpanded);
TreeView1.SelectedNodeChanged += new EventHandler(TreeView1_SelectedNodeChanged);
}
void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
_browseTextBox.Text = TreeView1.SelectedValue;
}
void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
if (e.Node.Value.EndsWith("\\"))
{
AddNodes(e.Node.Value, e.Node);
}
}
private TreeNode AddNodes(string path, TreeNode parentNode)
{
FileList objList = new FileList(path, "*.*");
TreeNode node = new TreeNode(path, path);
for (int index = 0; index < objList.Directories.Length; index++)
{
string directory = objList.Directories[index];
TreeNode objChildNode = new TreeNode(directory, path + "\\" + directory + "\\");
objChildNode.PopulateOnDemand = true;
objChildNode.Target = "_blank";
parentNode.ChildNodes.Add(objChildNode);
}
foreach (string file in objList.Files)
{
TreeNode objChildNode = new TreeNode(file, path + "\\" + file);
parentNode.ChildNodes.Add(objChildNode);
}
return node;
}
protected void _browseButton_Click(object sender, ImageClickEventArgs e)
{
TreeView1.Nodes.Clear();
if (UpdateBrowseTextBoxWithSlash())
{
TreeNode onjParent = new TreeNode(_browseTextBox.Text, _browseTextBox.Text);
onjParent.PopulateOnDemand = true;
TreeView1.Nodes.Add(onjParent);
TreeView1.CollapseAll();
}
else
{
error.Visible = true;
error.Text = "Please Enter valid path";
}
}
private bool UpdateBrowseTextBoxWithSlash()
{
if (_browseTextBox.Text.Length != 0)
{
if (
-1 == _browseTextBox.Text.LastIndexOf(".") &&
!_browseTextBox.Text.Substring(_browseTextBox.Text.Length - 1, 1).Equals("/") &&
!_browseTextBox.Text.Substring(_browseTextBox.Text.Length - 1, 1).Equals("\\")
)
{
if (_browseTextBox.Text.Substring(0, 1).Equals("\\") || -1 != _browseTextBox.Text.IndexOf(":\\"))
_browseTextBox.Text += "\\";
else
_browseTextBox.Text += "/";
return System.IO.Directory.Exists(_browseTextBox.Text);
}
else if (_browseTextBox.Text.LastIndexOf(".") > 0)
{
return System.IO.File.Exists(_browseTextBox.Text);
}
}
return true;
}
Have you looked at Imperfect Solution To TreeView? The author provides an interesting idea to omit postback when selecting a node by manually setting the NavigateUrl and SelectAction of each TreeNode. From first glance, it appears logical. The only thing missing is that it is not recursive so it can only handle one node level at a time.

ASP.NET Repeater not binding

I have issues.
One of them is this one.
I'm trying to bind a list of Hyperlinks to a repeater and I think my code looks all good, but my repeater is sadly lacking in anything. It's totally blank (Apart from the header, which is not databound).
I can't see where the problem is, so I'm hoping you guys can point it out to me.
Code:
Markup
<asp:Panel ID="pnlNavMenu" class="navigation" runat="server" Visible="true">
<div class="search-textbox"><div>
<asp:ImageButton ID="btnSearch" class="Search-Icon"
BackColor="White" runat="server" OnClick="btnSearch_Click"
ImageUrl="~/images/Mobile/mobile-search-icon.png" />
<asp:TextBox ID="txtSearch" runat="server" CssClass="Search" onblur="if(this.value == '') { this.value='Enter keyword or product code'; isSet=true; }"
onmouseover="if(this.value == 'Enter keyword or product code') { this.value='';isSet = true; }"
onmouseout="if(this.value == '' && !isSet) { this.value='Enter keyword or product code'; isSet=>false; }"
MaxLength="255" Text="Enter keyword or product code" ontextchanged="btnSearch_Click"/>
<asp:ImageButton ID="btnClear" class="Search-Cancel" BackColor="White" runat="server" OnClick="btnClear_Click" ImageUrl="~/images/Mobile/mobile-search-cancel.png" />
</div>
</div>
<asp:Panel ID="pnlComputers" runat="server" CssClass="nav-item" Visible="true">
<asp:Label id="lblComp" Text="Computers" runat="server" cssclass="Menu-Panel-Header"></asp:Label>
<asp:Repeater ID="rptComputers" runat="server">
<ItemTemplate><asp:HyperLink ID="hlCompCategories" runat="server" CssClass="nav-sub-item"><%#Eval("XW_WEBCATNAME") %></asp:HyperLink></ItemTemplate>
</asp:Repeater>
</asp:Panel
<asp:CollapsiblePanelExtender ID="cpe1" runat="Server" TargetControlID="pnlComputers" CollapsedSize="64" ExpandedSize="192" Collapsed="True" ExpandControlID="lblComp" CollapseControlID="lblComp" AutoCollapse="false" AutoExpand="False" ScrollContents="True" ExpandDirection="Vertical" />
</asp:Panel>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Customer"] is GPCUser)
{
hlLogInOut.Text = "Log Out";
hlLogInOut.NavigateUrl = "log-in.aspx?logout=1";
hlRegDetails.Text = "My Details";
hlRegDetails.NavigateUrl = "/update-details.aspx";
}
else
{
hlLogInOut.Text = "Log in";
hlLogInOut.NavigateUrl = "/log-in.aspx";
hlRegDetails.Text = "Register";
hlRegDetails.NavigateUrl = "/create-account.aspx";
}
BindCategories();
}
private void BindCategories()
{
if (!IsPostBack)
{
try
{
SqlConnection connect = new SqlConnection();
DataTable Data = new DataTable();
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=PCSQL";
connect.Open();
string query = null;
query = "SELECT * from dbo.STOCK_GROUPS WHERE XW_MAINGROUP = '1' ORDER BY XW_WEBCATNAME ASC";
SqlDataAdapter command = new SqlDataAdapter(query, connect);
command.Fill(Data);
connect.Close();
rptComputers.DataSource = Data;
}
catch (SqlException sqlEX)
{
sqlEX.ToString();
}
}
}
protected void rptComputers_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hlCompCategories = (HyperLink)e.Item.FindControl("hlCompCategories");
DataRowView dr = (DataRowView)e.Item.DataItem;
hlCompCategories.NavigateUrl = Page.ResolveUrl("~/" + "Computers" + "/" + dr["XW_URL"] + "/index.aspx");
if ((!object.ReferenceEquals(dr["xw_webcatname"], System.DBNull.Value)))
{
hlCompCategories.Text = (dr["xw_webcatname"]).ToString();
hlCompCategories.ToolTip = (dr["xw_webcatname"]).ToString();
}
else
{
hlCompCategories.Text = dr["groupname"].ToString();
hlCompCategories.ToolTip = dr["xw_webcatname"].ToString();
}
}
}
I'm pretty sure that the issue is in the ItemDataBound method because the rest of the panel loads fine (search bar and header, etc.) but none of my links are there.
After
rptComputers.DataSource = Data;
add
rptComputers.DataBind();
Otherwise it won't bind.
You might be missing AutoEventWireup=true in Page header in aspx file.
If not than please try to bind the repeater in the Page_Load event instead binding in Page_Init event.

Pass value from a Repeater row to a textbox on button click in asp.net C#

I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!

Cannot get the value on server side after callback

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.
}
}

Categories