Last item only being added to db - c#

I am trying to add some controls to a list but for some reason its only saving the last view to the db.
public List<tblPortalIandEValue> createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_iandevalues.Add(new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
return _iandevalues;
}
I think my problems lies in my save cause I'm calling this list add new and then returning it think I should be returning the record instead
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues=_dal.createIandERecord(_customerId , "mortagecic", mortagecic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString());
_iandevalues = _dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString());
_iandevalues.ForEach(n =>_dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}

Your problem is in your createIandERecord method since you are renewing the list everytime. change your code to this:
public tblPortalIandEValue createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
return new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
}
protected void btnSave_Click(object sender, EventArgs e)
{
List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
_customerId = Guid.NewGuid();
_iandevalues.Add(_dal.createIandERecord(_customerId, "mortagecic", mortagecic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString()));
_iandevalues.Add(_dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString()));
_iandevalues.ForEach(n => _dal.portalEntities.tblPortalIandEValues.Add(n));
_dal.portalEntities.SaveChanges();
}

Related

Get selected value from asp SharePoint DropDownList of custom class type

I am writing a SharePoint app. There I have page with drop down list. I have
a handler for SelectedIndexChanged. I want to get the selected value but as CustomObject and the only option I see is string. I tried SelectedValue and it is still string.
That's how I set the list:
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = //retrieving data
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x});
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
And that's one of the ways I tried:
protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
var index = groupingDropDownList.SelectedIndex;
CustomObject obj = (CustomObject)myDropDownList.Items[index].Value;
obj.DoSomething();
}
Is it even possible? Or do I have to have somewhere Dictionary with with objects?
You will want to leverage the html5 data attributes that you can then place onto the dropdown options. Here is an example of what you could do with your data.
// add Agencies' addresses as HTML5 data-attributes.
var agencies = agencyNames.ToList();
for (int i = 0; i < requesting_agency.Items.Count - 1; i++) {
requesting_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
servicing_agency.Items[i + 1].Attributes.Add("data-address",
agencies[i].address);
}
Then when processing the information you could do something like so.
var index = groupingDropDownList.SelectedIndex;
var selectedText = myDropDownList.Items[index].SelectedValue;
var selectedValue = myDropDownList.Items[index].Attributes["attribute"];
// put into obj
// do something with object
Let me know if you have any questions.
You 're binding a object (x => new { x.Name, Value = x}) to dropdown value, you should bind actual value to it.
Test demo:
public class CustomObject
{
public int ID { get; set; }
public string Name { get; set; }
public CustomObject(int _ID,string _Name)
{
this.ID = _ID;
this.Name = _Name;
}
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<CustomObject> customList = new List<CustomObject>();
customList.Add(new CustomObject(1,"test1"));
customList.Add(new CustomObject(2,"test2"));
myDropDownList.DataSource = customList.Select(x => new { x.Name, Value = x.ID });
myDropDownList.DataTextField = "Name";
myDropDownList.DataValueField = "Value";
myDropDownList.DataBind();
}
}

Issue displaying dictionary list values in listbox C#

I currently have two list boxes. One is to store the key and the second is to view the list associated with it.
The following code I have displays the key in the first listBox but fails to show the list in the second:
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
I have checked using the debugger to make sure that there is data contained in the dictionaries list so I am not sure what the problem is.
Can anyone point out where I maybe going wrong?
Thanks
Lists of 'naked' strings can't be used as a DataSource. You need to wrap them in a simple class with a real property. See here
After you have declared a simple string wrapper class:
class aString { public string theString { get; set; }
public aString(string s) { theString = s; }
public override string ToString() {return theString;} }
you can either change your Dictionary to contain a List<aString> or you can create a List<aString> from your Dictionary Values:
List<aString> aStringList = dict [src].Select(item => new aString(item) ).ToList();
listBoxDST.DataSource = aStringList ;
The ListBox can now display the aString.ToString() values.
try this man
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.SelectNodes("pdml/packet/proto[#name='ip']/#showname");
foreach (XmlAttribute attribute1 in node)
{
string ip = attribute1.Value;
var arr = ip.Split(); var src = arr[5]; var dst = arr[8];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
}
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}

How to get object values using object ID property in C#

this is my first experience on windows phone 8 application development.
I have a problem which I mention below, could you please help me to figure out it.
I show data from ActivityViewModel via Data Binding in Activities.xaml
When user tap to activity item, I send ActivityID to ActivityDetails.xaml.
I am trying to call object which I created as AccountAction by using ActivityID.
How can I get object values (ActivityImage, ActivityName, ActivityAmont ...) by using ActivityID in ActivityDetails.xaml.cs?
ActivityViewModel:
public class ActivityViewModel
{
public ObservableCollection<AccountAction> ActivityItemCollection { get; set; }
public ActivityViewModel()
{
ActivityItemCollection = new ObservableCollection<AccountAction>();
ActivityItemCollection.Add(new AccountAction()
{
ActivityID = "SP0001",
ActivityImage = "/Images/Logos/e-bay.png"
ActivityName = "E-Bay",
ActivityAmount = "100,00",
ActivityDate = "Today",
ActivityHour = "11:49"
});
.
.
.
}
}
Activities.xaml.cs
private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var _ActivityID = Convert.ToString(((StackPanel)sender).Tag);
NavigationService.Navigate(new Uri("/ActivityDetails.xaml?ActivityID=" + _ActivityID, UriKind.Relative));
}
ActivityDetails.xaml.cs
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string ActivityID = "";
if (NavigationContext.QueryString.TryGetValue("ActivityID", out ActivityID))
{
ReferanceNumber.Text = ActivityID;
}
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string ActivityID;
if (e.IsNavigationInitiator && this.NavigationContext.QueryString.TryGetValue("ActivityID", out ActivityID))
{
ActivityID= int.Parse(ActivityID);
}
}
EDIT:
You can get the data related to activityid by using linq
AccountAction result = ActivityItemCollection.FirstOrDefault(act=>act.ActivityID == ActivityID);
Then you can get object values like result.ActivityName

Adding a row in a gridview from a Dictionary<Key,Value>

I have a LinkButton on my Page1.aspx with the fields
Attached below is the image of page1.aspx. And a gridview in Page2.aspx.. When i click onto the linkbutton , the page redirects to Page2.aspx and fill the gridview with the required fields..
where the Required Fields are
Image,
Name = Black Cap,
Title = Topi,
Price = 1200
The Code of Page1.aspx:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Dictionary<string, string> OrderDict = new Dictionary<string, string>();
if (e.CommandName == "orderClick")
{
string value = e.CommandArgument.ToString();
string id = this.ListView1.DataKeys[e.Item.DataItemIndex].Value.ToString();
OrderDict.Add(id, value);
Session["Order"] = OrderDict;
Response.Redirect("Page2.aspx");
Response.Write(OrderDict);
}
}
The Code of Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> Dictionary = (Dictionary<string, string>)Session["Order"];
//Regex reg = new Regex(#"\[([^\]]+)\]([^\[]+)");
if (Dictionary != null)
{
GridView1.DataSource = Dictionary;
//Dictionary = reg.Matches(Dictionary.ToString()).Cast<Match>().ToDictionary(x => x.Groups[1].Value
// , x => x.Groups[2].Value.Trim());
//string slit = Dictionary.s
this.GridView1.DataBind();
//this.GridView1.DataSource = Dictionary;
Response.Write(Dictionary.Values.Count);
}
}
This is the first time I see code that binds to a dictionary. You should bind to the Keys property of the dictionary.
// Change your original line in Page_Load to this... The variable name conflicts with the class name
Dictionary<string, string> orderDictionary = (Dictionary<string, string>)Session["Order"];
// Bind like this:
GridView1.DataSource = orderDictionary.Keys;
See Dictionary(Of TKey, TValue).Keys Property
Have you considered creating a class that represents the list of items you're storing in the Session? For example:
public class SelectedOrder
{
public string ID { get; set; }
public string Value { get; set; }
}
// Then in your ListView ItemCommand in Page1.aspx
var orders = ((List<SelectedOrder>)Session["Order"]) ?? new List<SelectedOrder>();
orders.Add(new SelectedOrder() { ID = id, Value = value });
Session["Order"] = orders;
// And in Page2
List<SelectedOrder> orders = (List<SelectedOrder>)Session["Order"];
if (null != orders) {
GridView1.DataSource = orders;
GridView1.DataBind();
// Rest of code follows...
}
I think this will be an easier approach to deal with in your code.

Why does this not work?

I have a class which will act as variables to store data from textboxes:
public class Business
{
Int64 _businessID = new Int64();
int _businessNo = new int();
string _businessName;
string _businessDescription;
public Int64 BusinessID
{
get { return Convert.ToInt64(_businessID.ToString()); }
}
public int BusinessNo
{
get { return _businessNo; }
set { _businessNo = value; }
}
public string BusinessName
{
get { return _businessName; }
set { _businessName = value; }
}
public string BusinessDescription
{
get { return _businessDescription; }
set { _businessDescription = value; }
}
I then have the code to store the data from the textbox into a session and into a list (there can be many businesses uploaded to the database at one time) - database irrelevent for now. I then want to display the list of businesses stored into the session onto the gridview: (b = class business)
List<Business> businessCollection = new List<Business>();
protected List<Business> GetBusinesses()
{
return (List<Business>)Session["Business"];
}
protected void btnRow_Click(object sender, EventArgs e)
{
if (Session["Business"] != null)
businessCollection = (List<Business>)Session["Business"];
Business b = new Business();
b.BusinessNo = Convert.ToInt32(txtBNo.Text);
b.BusinessName = txtBName.Text;
b.BusinessDescription = txtBDesc.Text;
businessCollection.Add(b);
GridView1.DataSource = GetBusiness();
GridView1.DataBind();
}
It doesn't seem to add the list to the gridview, can someone help?
Debug your code and ensure that if (Session["Business"] != null) actually evaluates to true.
If it is false then you are adding to a list that is never returned from GetBusinesss
Without any more information you can rewrite it like this:
List<Business> businessCollection = new List<Business>();
protected List<Business> GetBusinesses()
{
if (Session["Business"] == null)
return businessCollection;
else
return (List<Business>)Session["Business"];
}
protected void btnRow_Click(object sender, EventArgs e)
{
Business b = new Business();
b.BusinessNo = Convert.ToInt32(txtBNo.Text);
b.BusinessName = txtBName.Text;
b.BusinessDescription = txtBDesc.Text;
var currentCollection = GetBusinesses();
currentCollection.Add(b);
GridView1.DataSource = currentCollection;
GridView1.DataBind();
}
I personally wouldn't do it like this, as it seems like you need an assignment to Session["Business"] but I don't want to change the logic of your code.
Update
I wanted to update this with what I think you wanted to accomplish.
protected List<Business> GetBusinesses()
{
if (Session["Business"] == null)
Session["Business"] = new List<Business>();
return (List<Business>)Session["Business"];
}
protected void btnRow_Click(object sender, EventArgs e)
{
Business b = new Business();
b.BusinessNo = Convert.ToInt32(txtBNo.Text);
b.BusinessName = txtBName.Text;
b.BusinessDescription = txtBDesc.Text;
var currentCollection = GetBusinesses();
currentCollection.Add(b);
GridView1.DataSource = currentCollection;
GridView1.DataBind();
}
It seems you are not assigning anything to Session["Business"]
There's a very strong chance that you're problem is caused by the fact that you are referencing the Business List object inconsistently. You've created an accessor for this object, so use it everywhere.
This:
if (Session["Business"] != null)
businessCollection = (List<Business>)Session["Business"];
Should be:
var businessCollection = GetBusiness();
Note the use of var: I suspect defining businessCollection as a member variable is part of the problem. In any case it is bad design if your intent is to store the list in the session. So I would also remove the member declaration for businessCollection and stick with a locally scoped variable.

Categories