List stays populated after PostBack - c#

I have a .aspx application where the user inputs a name and that name is added to a list. This can be done up to five times. When the user clicks the button, the first name entered will display in the first label. When the user inputs another name and clicks the button the first label remains the same and the next label displays the new name and so on. My problem is the list is reset on PostBack. I am trying to use ViewState to help solve this with no success. Any help is greatly appreciated.
Edit: I got it working so thank you everybody for your help. There is still a lot of room for improvement but this is a great starting point.
[Serializable]
class Recipient
{
public string Fname { get; set; }
public string MInit { get; set; }
public string Lname { get; set; }
public string Suffix { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnEnter_Click(object sender, EventArgs e)
{
Recipient recipients = new Recipient();
List<string> FName = (List<string>)ViewState["recipientList"];
List<string> MInit = (List<string>)ViewState["recipientList"];
List<string> LName = (List<string>)ViewState["recipientList"];
if (FName == null && MInit == null && LName == null)
{
FName = new List<string>();
MInit = new List<string>();
LName = new List<string>();
}
recipients.Fname = txtFName.Text;
recipients.MInit = txtMinit.Text;
recipients.Lname = txtLName.Text;
FName.Add(recipients.Fname);
MInit.Add(recipients.MInit);
LName.Add(recipients.Lname);
ViewState["recipientList"] = FName;
ViewState["recipientList"] = MInit;
ViewState["recipientList"] = LName;
if (FName.Count == 1 && MInit.Count == 1 && LName.Count == 1)
{
lblFName.Text = FName[0] + " " + MInit[0] + " " + LName[0];
}
if (FName.Count == 4 && MInit.Count == 4 && LName.Count == 4)
{
lblFName1.Text = FName[1] + " " + MInit[2] + " " + LName[3];
}
}

I'm not sure the purpose of Recipient class. Anyhow, you want to instantiate Recipient list before adding a recipient.
<asp:TextBox runat="server" ID="txtFName" /><br />
<asp:Button runat="server" ID="btnEnter" Text="Submit" OnClick="btnEnter_Click" /><br />
<asp:Label runat="server" ID="lblFName" /><br />
<asp:Label runat="server" ID="lblFName1" /><br />
<asp:Label runat="server" ID="lblFName2" /><br />
<asp:Label runat="server" ID="lblFName3" /><br />
<asp:Label runat="server" ID="lblFName4" /><br />
[Serializable]
public class Recipient
{
public string name { get; set; }
}
public List<Recipient> recipientList
{
get
{
if (ViewState["recipientList"] != null)
return (List<Recipient>)ViewState["recipientList"];
return new List<Recipient>();
}
set { ViewState["recipientList"] = value; }
}
protected void btnEnter_Click(object sender, EventArgs e)
{
List<Recipient> recipient = recipientList;
recipient.Add(new Recipient{ name = txtFName.Text.Trim()});
recipientList = recipient;
int count = recipient.Count;
if (count == 1)
lblFName.Text = recipientList[0].name;
if (count > 1)
lblFName1.Text = recipientList[1].name;
if (count > 2)
lblFName2.Text = recipientList[2].name;
if (count > 3)
lblFName3.Text = recipientList[3].name;
if (count > 4)
lblFName4.Text = recipientList[4].name;
}

Do you really need a list for this? You could do...
if(lblFName.Text.Equals(String.Empty))
{
lblFName.Text = value;
}
else if(lblFName1.Text.Equals(String.Empty))
{
lblFName1.Text = value;
}//and so on...

If a postback is firing when you hit the enter button. Then you need to handle rebuilding the list in the Page_Load. Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
recipientList = (List<string>)ViewState["recipientList"];
//now load the list
}
}

Related

get data from two different pages

Here is my problem. suppose by example, when I click on repeater row id then it will transfer to particular customers invoice.
But in customer invoice page, it opens only when customer Id logged in. So here two different pages accessing one page data. my code is as below.
In repeater's page.
<th>
<asp:LinkButton ID ="lnkbtnStmt" Text ="Statement" OnClick ="lnkbtnStmt_Click" runat="server"></asp:LinkButton>
<asp:HiddenField ID ="hfStmt" runat ="server" Value='<% #Eval("No")%>'/>
</th>
in repeater .cs page :
public void lnkbtnStmt_Click(object sender, EventArgs e)
{
int rptIndex = ((RepeaterItem)((LinkButton)sender).NamingContainer).ItemIndex;
string hfItem = Convert.ToString(((HiddenField)RptEmpCustInvoise.Items[rptIndex].FindControl("hfStmt")).Value);
Customer_Ledger_Entries custlist = new Customer_Ledger_Entries();
List<Customer_Ledger_Entries_Filter> cFilter = new List<Customer_Ledger_Entries_Filter>();
Customer_Ledger_Entries_Filter cfield = new Customer_Ledger_Entries_Filter();
cfield.Field = Customer_Ledger_Entries_Fields.Customer_No;
cfield.Criteria = hfItem;
cFilter.Add(cfield);
Customer_Ledger_Entries[] culist = cls.wsCustInvoice.ReadMultiple(cFilter.ToArray(), null, 1);
if (culist.Length > 0)
{
Response.Redirect("frmCustomerInvoice.aspx?Customer_No=" + hfItem);
}
}
And in another Customer page.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
GetOpeningBal();
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
GetClosingBal();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), string.Empty, "alert('" + ex.Message.ToString() + "');", true);
}
}
In this page,bindCustInvoice() method works when customer get logged in and CustInvoice("empCustId"); method works when we clicked on repeater id.
can any one give me solution?
When you clicked on Repeater Id , try to send the Page Name from Query String . and check the page name in your another customer page
Pseudo code
string PageName ="";
if(Request.QueryString["PageName"] != null)
{
PageName= Request.QueryString["PageName"];
}
if(PageName != "")
{
string empCustId = Request.QueryString["Customer_No"];
if (empCustId.Length != 0)
{
CustInvoice("empCustId");
}
}
else{
bindCustInvoice(objSession.getSession(HttpContext.Current, "NonEmpCode"));
}

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!

GridView with objectDataSource is returning NULL cell values in RowEditing and RowUpdating events

I am using an ObjectDataSource with a GridView as shown below. It's wrapped in an UpdatePanel. When user presses a button outside this UpdatePanel, it should populate the gridview by feeding the ObjectSource Select method some seed values. That part is working fine - the gridView initializes successfully when the Select method is called. When the user proceeds to press the Edit button, the gridView also successfully transforms into edit mode with editable TextBox controls. That part also works fine, but I've tried to inspect the GridViewRow.Cell[i].Text and the GridViewRow.Cell[i].Controls[j] values during this transition and it is always NULL for every cell in the gridview.
Finally, when the Update methods are called on the underlying ObjectSource, all of the parameters passed into the Update method are effectively NULL. In short, even though the user sees the content of the cells, the code is never able to capture this content - it only receives NULL. Note, I implement several DataBinds on the objectsource during !PostBack and the RowEditing and RowUpdating events.
Any ideas why I can't capture the String content in these Cells?
Here is the markup:
<asp:UpdatePanel ID="PgimUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField ID="hdnShowPgim" runat="server"/>
<div id="jsPgimPanel">
<asp:ObjectDataSource ID="pgimObjectSource" Runat="server" TypeName="CarePlanModifier.Models.PgimMapping" SelectMethod="GetPgims" EnablePaging="True" SelectCountMethod="TotalNumberOfPgims" UpdateMethod="UpdatePgims" InsertMethod="UpdatePgims" DeleteMethod="SoftDeletePgims" OnUpdating="pgimObjectSource_Updating" OnSelecting="pgimObjectSource_Selecting" >
<SelectParameters>
<asp:querystringparameter name="MatchCode" querystringfield="MatchCode" defaultvalue="0" />
<asp:querystringparameter name="CprId" querystringfield="CprId" defaultvalue="0" />
<asp:querystringparameter name="SessionUser" querystringfield="SessionUser" defaultvalue="0" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Type="Int32" Name="Id"></asp:Parameter>
<asp:Parameter Type="String" Name="Icd1Code"></asp:Parameter>
<asp:Parameter Type="String" Name="MatchCode"></asp:Parameter>
<asp:Parameter Type="String" Name="Problems"></asp:Parameter>
<asp:Parameter Type="String" Name="Goals"></asp:Parameter>
<asp:Parameter Type="String" Name="Interventions"></asp:Parameter>
<asp:Parameter Type="Int32" Name="CprId"></asp:Parameter>
<asp:Parameter Type="String" Name="EditUser"></asp:Parameter>
</UpdateParameters>
</asp:ObjectDataSource>
<asp:GridView ID="gridPgim" Runat="server" DataSourceID="pgimObjectSource" AutoGenerateColumns="False" AllowPaging="True" BorderWidth="1px" BackColor="White" CellPadding="3" BorderStyle="Solid" BorderColor="#999999" ForeColor="Black" GridLines="Vertical" pagesize="10" OnRowEditing="gridPgim_RowEditing" OnRowCancelingEdit="gridPgim_RowCancelingEdit" OnRowUpdating="gridPgim_RowUpdating" OnRowCommand="gridPgim_RowCommand" DataKeyNames="Id, MatchCode,CprId, EditUser">
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle Font-Bold="True" BackColor="Black" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="False" ></asp:CommandField>
<asp:BoundField Visible="false" ReadOnly="True" HeaderText="Id" InsertVisible="False" DataField="Id" SortExpression="Id"></asp:BoundField>
<asp:BoundField Visible="false" ReadOnly="True" HeaderText="Icd1Code" DataField="Icd1Code" SortExpression="Icd1Code"></asp:BoundField>
<asp:BoundField Visible="false" ReadOnly="True" HeaderText="MatchCode" DataField="MatchCode" SortExpression="MatchCode"></asp:BoundField>
<asp:BoundField Visible="false" ReadOnly="True" HeaderText="CprId" InsertVisible="False" DataField="CprId" SortExpression="CprId"></asp:BoundField>
<asp:BoundField Visible="false" ReadOnly="True" HeaderText="EditUser" InsertVisible="False" DataField="EditUser" SortExpression="EditUser"></asp:BoundField>
<asp:TemplateField HeaderText="Problems" SortExpression="Problems">
<EditItemTemplate>
<asp:TextBox ID="txtProblems" TextMode="MultiLine" runat="server" TextWrapping="Wrap" Rows="4"
AcceptsReturn="False" VerticalScrollBarVisibility="Visible"
Text='<%# Bind("Problems") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEditProblems" runat="server" Text='<%# Bind("Problems") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Goals" SortExpression="Goals">
<EditItemTemplate>
<asp:TextBox ID="txtGoals" runat="server" TextMode="MultiLine" TextWrapping="Wrap" Rows="4" AcceptsReturn="False" VerticalScrollBarVisibility="Visible" Text='<%# Bind("Goals") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEditGoals" runat="server" Text='<%# Bind("Goals") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Interventions" SortExpression="Interventions">
<EditItemTemplate>
<asp:TextBox ID="txtInterventions" runat="server" TextMode="MultiLine" TextWrapping="Wrap" Rows="4" AcceptsReturn="False" VerticalScrollBarVisibility="Visible" Text='<%# Bind("Interventions") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEditInterventions" runat="server" Text='<%# Bind("Interventions") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
</div>
<script type="text/javascript" src="Scripts/jquery.jspanel.min.js"></script>
<link rel="stylesheet" type="text/css" href="Scripts/jquery.jspanel.min.css"/>
<link rel="stylesheet" type="text/css" href="Scripts/jsglyph.css"/>
<script type="text/javascript">
var pgim;
function clearPanel() {
//alert('0');
pgim.close();
//alert('1');
};
function displayPanel() {
//alert('0');
if (pgim != null) {
pgim.close();
}
//alert('1');
pgim = $.jsPanel({
content: $('div#jsPgimPanel'),
title: "PGIM",
position: "center right",
theme: "light",
overflow: 'visible',
size: { width: 800, height: 450 },
});
};
function rePanel() {
alert('3');
pgim.reloadContent();
alert('4');
};
</script>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gridDiagnoses" EventName="RowCommand"/>
</Triggers>
</asp:UpdatePanel>
Here is the code-behind event methods:
protected void btnFindPgim_Load(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
//PgimUpdatePanel.Triggers.Add(new PostBackTrigger{ ControlID=btn.UniqueID });
PgimUpdatePanel.Triggers.Add(new AsyncPostBackTrigger { ControlID = btn.UniqueID, EventName = "Click" });
}
protected void gridPgim_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
gridPgim.EditIndex = e.NewEditIndex;
string diagCode = hdnSelectedDiagCode.Value;
int cprId = Convert.ToInt32(hdnCprId.Value);
CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
displayFiles(Convert.ToInt32(hdnCprId.Value), xCpr.Client);
//GridView gv = (GridView)sender;
//gv.EditIndex = e.NewEditIndex;
//gv.DataBind();
BindPgimGrid(diagCode, cprId);
//ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "displayPanel();", true);
//ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "rePanel();", true);
}
protected void gridPgim_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
displayFiles(Convert.ToInt32(hdnCprId.Value), xCpr.Client);
//Reset the edit index.
gridPgim.EditIndex = -1;
ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
}
protected void gridPgim_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
ISession session = HiHibernateUtil.GetCurrentSession();
CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
try
{
PgimMapping pm = new PgimMapping();
if (e.NewValues["Problems"] != null)
{
pm.Problems = (string)e.NewValues["Problems"];
}
GridView gv = (GridView)sender;
for (int i = 0; i < gv.Columns.Count; i++)
{
DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell, DataControlRowState.Edit, true);
}
foreach (DictionaryEntry de in e.NewValues)
{
string dkey = (string)de.Key;
if ( dkey.Equals("Icd1Code", StringComparison.CurrentCultureIgnoreCase) )
{
pm.Icd1Code = (string)de.Value;
}
if (dkey.Equals("CprId", StringComparison.CurrentCultureIgnoreCase))
{
pm.CprId = Convert.ToInt32((string)de.Value);
}
if (dkey.Equals("MatchCode", StringComparison.CurrentCultureIgnoreCase))
{
pm.MatchCode = (string)de.Value;
}
if (dkey.Equals("MatchCode", StringComparison.CurrentCultureIgnoreCase))
{
pm.MatchCode = (string)de.Value;
}
if (dkey.Equals("Problems", StringComparison.CurrentCultureIgnoreCase))
{
pm.Problems = (string)de.Value;
}
if (dkey.Equals("Goals", StringComparison.CurrentCultureIgnoreCase))
{
pm.Goals = (string)de.Value;
}
if (dkey.Equals("Interventions", StringComparison.CurrentCultureIgnoreCase))
{
pm.Interventions = (string)de.Value;
}
}
if (pm.CprId < 1)
{
throw new Exception("ERROR the 'cprId' value is invalid for " + pm.CprId);
}
if (String.IsNullOrEmpty(pm.Problems) || pm.Problems.Length < 3)
{
throw new Exception("ERROR the 'problem' value is empty for " + pm.MatchCode);
}
if (String.IsNullOrEmpty(pm.Goals) || pm.Goals.Length < 3)
{
throw new Exception("ERROR the 'goal' value is empty for " + pm.MatchCode);
}
pm.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
pm.Active = 0;
pm.AddedDate = DateTime.Now;
pm.EditUser = xCpr.SessionUser.Username;
// now add the PGIM to this Care Plan
CareNeeds cneeds = new CareNeeds();
cneeds.Active = 0;
cneeds.CprId = pm.CprId;
cneeds.EditUser = pm.EditUser;
cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
cneeds.Goal = pm.Goals;
cneeds.Problem = pm.Problems;
cneeds.Interventions = pm.Interventions;
cneeds.AddedDate = DateTime.Now;
using (ITransaction txn = session.BeginTransaction())
{
session.Save(pm);
session.Save(cneeds);
txn.Commit();
}
//Reset the edit index.
gridPgim.EditIndex = -1;
}
catch (System.Exception ee)
{
log.Error("gridPgim_RowUpdating() " + ee.Message);
log.Error("gridPgim_RowUpdating() " + ee.StackTrace);
LabelErrorMessages2.CssClass = "errorlabel";
LabelErrorMessages2.Text = LabelErrorMessages.Text + " " + ee.Message;
}
finally
{
session.Flush();
session.Close();
}
}
protected void gridPgim_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
BindPgimGrid(hdnSelectedDiagCode.Value, Convert.ToInt32(hdnCprId.Value));
GridViewRow row = gridPgim.Rows[gridPgim.EditIndex];
} else if ( e.CommandArgument == "Edit" )
{
}
ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "displayPanel();", true);
}
Finally, here is the DAL object (which is also mapped to a nHibernate mapping) but with some methods removed to shorten this post.
public class PgimMapping
{
private static readonly log4net.ILog log = LogManager.GetLogger(typeof(PgimMapping));
public PgimMapping(string diagCode, int cprId, string suser)
{
this.matchCode = diagCode;
this.cprId = cprId;
this.sessionUser = suser;
}
private string sessionUser = null;
private string matchCode = null;
public string MatchCode
{
get { return matchCode; }
set { matchCode = value; }
}
private int id = 0;
public virtual int Id
{
get { return id; }
set { id = value; }
}
private string icd1Code = null;
public virtual string Icd1Code
{
get { return icd1Code; }
set { icd1Code = value; }
}
private string icd9Code = null;
public virtual string Icd9Code
{
get { return icd9Code; }
set { icd9Code = value; }
}
private string description = null;
public virtual string Description
{
get { return description; }
set { description = value; }
}
private string problems = null;
public virtual string Problems
{
get { return problems; }
set { problems = value; }
}
private string goals = null;
public virtual string Goals
{
get { return goals; }
set { goals = value; }
}
private string interventions = null;
public virtual string Interventions
{
get { return interventions; }
set { interventions = value; }
}
private string measures = null;
public virtual string Measures
{
get { return measures; }
set { measures = value; }
}
private string discussWDr = null;
public virtual string DiscussWDr
{
get { return discussWDr; }
set { discussWDr = value; }
}
private string memberProblems = null;
public virtual string MemberProblems
{
get { return memberProblems; }
set { memberProblems = value; }
}
private string memberGoals = null;
public virtual string MemberGoals
{
get { return memberGoals; }
set { memberGoals = value; }
}
private DateTime? addedDate = null;
public virtual DateTime? AddedDate
{
get { return addedDate; }
set { addedDate = value; }
}
private string editUser = null;
public virtual string EditUser
{
get { return editUser; }
set { editUser = value; }
}
private DateTime? modifyDate = null;
public virtual DateTime? ModifyDate
{
get { return modifyDate; }
set { modifyDate = value; }
}
private int gmtOffset = 0;
public virtual int GmtOffset
{
get { return gmtOffset; }
set { gmtOffset = value; }
}
private int active = 0;
public virtual int Active
{
get { return active; }
set { active = value; }
}
private int cprId = 0;
public int CprId
{
get { return cprId; }
set { cprId = value; }
}
public void UpdatePgims(int Id, string Icd1Code, string MatchCode, int CprId, string Problems, string Goals, string Interventions, string EditUser)
{
ISession session = HiHibernateUtil.GetCurrentSession();
try
{
if (CprId < 1)
{
throw new Exception("ERROR the 'cprId' value is invalid for " + CprId);
}
if (String.IsNullOrEmpty(Problems) || Problems.Length < 3)
{
throw new Exception("ERROR the 'problem' value is empty for " + MatchCode);
}
if (String.IsNullOrEmpty(Goals) || Goals.Length < 3)
{
throw new Exception("ERROR the 'goal' value is empty for " + MatchCode);
}
PgimMapping pm = new PgimMapping(Icd1Code, CprId, EditUser);
pm.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
pm.Goals = Goals;
pm.Problems = Problems;
pm.Interventions = Interventions;
pm.Icd1Code = Icd1Code;
pm.Active = 0;
pm.AddedDate = DateTime.Now;
pm.CprId = CprId;
pm.MatchCode = MatchCode;
pm.sessionUser = EditUser;
// now add the PGIM to this Care Plan
CareNeeds cneeds = new CareNeeds();
cneeds.Active = 0;
cneeds.CprId = CprId;
cneeds.EditUser = EditUser;
cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
cneeds.Goal = Goals;
cneeds.Problem = Problems;
cneeds.Interventions = Interventions;
cneeds.AddedDate = DateTime.Now;
using (ITransaction txn = session.BeginTransaction())
{
session.Save(pm);
session.Save(cneeds);
txn.Commit();
}
}
catch (Exception ee)
{
log.Error("UpdatePgims() " + ee.Message);
log.Error("UpdatePgims() " + ee.StackTrace);
}
finally
{
session.Flush();
session.Close();
}
}
}
I was able to achieve what I needed (although not exactly as I hoped and with many compromises) with the following bit of code.
protected void gridPgim_RowCommand(Object sender, GridViewCommandEventArgs e)
{
ISession session = HiHibernateUtil.GetCurrentSession();
CarePlanReview xCpr = (CarePlanReview)Request.RequestContext.HttpContext.Session["xCpr"];
if (e.CommandName == "Edit")
{
GridViewRow row = gridPgim.Rows[Convert.ToInt32(e.CommandArgument)];
TableCellCollection tbc = row.Cells;
Object[] objArray = new Object[row.Cells.Count];
tbc.CopyTo(objArray, 0);
DataControlFieldCell problemsCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimProblemIndex"))];
//String txtProb = ((Label)problemsCf.Controls[1]).Text;
String txtProb = problemsCf.Text;
DataControlFieldCell goalCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimGoalIndex"))];
//String txtGoal = ((Label)goalCf.Controls[1]).Text;
String txtGoal = goalCf.Text;
DataControlFieldCell interventionCf = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimInterventionIndex"))];
//String txtInt = ((Label)interventionCf.Controls[1]).Text;
String txtInt = interventionCf.Text;
DataControlFieldCell diagCode = (DataControlFieldCell)objArray[Convert.ToInt32(Utility.getAppSetting("pgimDiagIndex"))];
String txtdiag = diagCode.Text;
int cprId = Convert.ToInt32(hdnCprId.Value);
// now add the PGIM to this Care Plan
CareNeeds cneeds = new CareNeeds();
cneeds.Active = 0;
cneeds.CprId = cprId;
cneeds.EditUser = xCpr.SessionUser.Username;
cneeds.GmtOffset = Convert.ToInt32(Utility.getAppSetting("gmtOffset"));
cneeds.Goal = txtGoal;
cneeds.Problem = txtProb;
cneeds.Interventions = txtInt;
cneeds.Icd1Code = txtdiag;
cneeds.AddedDate = DateTime.Now;
using (ITransaction txn = session.BeginTransaction())
{
session.Save(cneeds);
txn.Commit();
}
careNeedsDataSource.SelectParameters.Clear();
careNeedsDataSource.SelectParameters.Add("CprId", System.Data.DbType.Int32, Convert.ToString(cprId));
careNeedsDataSource.Select();
careNeedsDataSource.DataBind();
}
ScriptManager.RegisterStartupScript(Page, typeof(Page), "jsPanel", "clearPanel();", true);
}

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

Assistance with SQLDataSource Filtering with Mixed Control Types

I have been looking into DataSource Filtering and the complexity of my page app is making my logic wade through mud.
I have a Gridview that Displays 3/17 Values from a Datasource.
I want to run a filter on 3 DropDowns and 3 Checkboxes against the datasource. The 3 DDLs have a default value of String.Empty at Index 0 and are populated by another DS on Page load (!IsPostBack).
My Issues:
When the page loads there is nothing in the gridview. Empty DDL Values should be skipped.
The last check box should represent whether (Part_Catalog.PartCount > 0).
Currently filters are defined in the datasource, but due to the above conditions I need to do some processing in the cs file. What I'm unsure of is If I need to move the Entire DS to the code behind, the filters, or just the filter conditions.
Also I'm not sure what events to wire into.
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
EnableCaching="true"
DataSourceMode="DataSet"
ConnectionString="<%$ ConnectionStrings:inventory_v2ConnectionString %>"
SelectCommand="SELECT ID, OEMPartCode, PartCode2, UsedByOEM, ItemType, GroupType, PartCount, PartDesc, PartComment, PartMin, PartActive, MFRPartNumber, PartCapacity, PreTurnRequired, AssemblyPart, PartImage, PartImage2, NonInventoryPart FROM dbo.Part_Catalog"
FilterExpression="UsedByOEM = '{0}' AND ItemType = '{1}' AND GroupType = '{2}' OR (UsedByOEM = '{0}' OR ItemType = '{1}' OR GroupType = '{2}') OR (UsedByOEM = '{0}' OR ItemType = '{1}' AND GroupType = '{2}') OR (UsedByOEM = '{0}' AND ItemType = '{1}' OR GroupType = '{2}')">
<FilterParameters>
<asp:ControlParameter Name="UsedByOEM" ControlID="DDL_OEM" PropertyName="SelectedValue" />
<asp:ControlParameter Name="ItemType" ControlID="DDL_ItemTypes" PropertyName="SelectedValue" />
<asp:ControlParameter Name="GroupType" ControlID="DDL_GroupTypes" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="DDL_OEM" runat="server" AutoPostBack="True" AppendDataBoundItems="True"></asp:DropDownList>
<asp:DropDownList ID="DDL_ItemTypes" runat="server" AutoPostBack="True" AppendDataBoundItems="True"></asp:DropDownList>
<asp:DropDownList ID="DDL_GroupTypes" runat="server" AutoPostBack="True" AppendDataBoundItems="True"></asp:DropDownList>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="True" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" Checked="True" />
protected void BindOEMs()
{
SqlConnection connectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["inventory_v2ConnectionString"].ConnectionString);
connectionString.Open();
SqlCommand cmd = new SqlCommand("SELECT [Manufacturer], [ID] FROM [Models_OEMs] ORDER BY [Manufacturer]", connectionString);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
connectionString.Close();
DDL_OEM.DataSource = ds;
DDL_OEM.DataTextField = "Manufacturer";
DDL_OEM.DataValueField = "ID";
DDL_OEM.DataBind();
DDL_OEM.Items.Insert(0, new ListItem(String.Empty, "0"));
}
Figured it out now. I added the line below to page_load (!isPostBack) so filter applies at first load.
if (gvFilter.OEM == null || gvFilter.OEM == 0 ) { Filter_DataSet(null, null); }
Created a custom Filter object with my categories:
public class Filters
{
private int oem;
private int item;
private int group;
private bool active;
private bool ninventoried;
private bool stocked;
public int OEM
{
set { oem = value; }
get { return oem; }
}
public int Item
{
set { item = value; }
get { return item; }
}
public int Group
{
set { group = value; }
get { return group; }
}
public bool Active
{
set { active = value; }
get { return active; }
}
public bool Ninventoried
{
set { ninventoried = value; }
get { return ninventoried; }
}
public bool Stocked
{
set { stocked = value; }
get { return stocked; }
}
}
Then I created a method to apply the filters to the Datasource and set all filter control events to this method:
protected void Filter_DataSet(object sender, EventArgs e)
{
DetailsView1.Visible = false;
string FEString= String.Empty;
gvFilter.OEM = Convert.ToInt32(DDL_OEM.SelectedValue);
gvFilter.Item = Convert.ToInt32(DDL_ItemTypes.SelectedValue);
gvFilter.Group = Convert.ToInt32(DDL_GroupTypes.SelectedValue);
if (CheckBox1.Checked == true) { gvFilter.Active = true; } else { gvFilter.Active = false; }
if (CheckBox2.Checked == true) { gvFilter.Ninventoried = true; } else { gvFilter.Ninventoried = false; }
if (CheckBox3.Checked == true) { gvFilter.Stocked = true; } else { gvFilter.Stocked = false; }
if (gvFilter.OEM >0)
{
FEString += "UsedByOEM = " + gvFilter.OEM.ToString();
}
if (gvFilter.Item > 0)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "ItemType = " + gvFilter.Item.ToString();
}
if (gvFilter.Group > 0)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "GroupType = " + gvFilter.Group.ToString();
}
if (gvFilter.Active == true)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "PartActive = " + gvFilter.Active.ToString();
}
if (gvFilter.Active == false)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "PartActive = " + gvFilter.Active.ToString();
}
if (gvFilter.Ninventoried == true)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "NonInventoryPart = " + gvFilter.Ninventoried.ToString();
}
if (gvFilter.Ninventoried == false)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "NonInventoryPart = " + gvFilter.Ninventoried.ToString();
}
if (gvFilter.Stocked == true)
{
if (FEString.Length > 0) { FEString += " AND "; }
FEString += "PartCount > 0 ";
}
//if (gvFilter.Stocked == false)
//{
// if (FEString.Length > 0) { FEString += " AND "; }
// FEString += "PartCount <= 0 ";
//}
SqlDataSource1.FilterExpression = FEString;
}

Categories