linq query and foreign used to create data - c#

I got problem facing the problem that i am using the table, "locationstation" and create station and location inside and both the station and location were linked to locationstation by their primary key. I have already successfully showed their data in the combo box but the problem now is that i don't know how to select the data inside the combo box and save the data in the locationstation table.
private void btnCreate_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
//station selectStation = cbStation.SelectedItem as station;
//location selectLocation = cbLocation.SelectedItem as location;
string selectStation = cbStation.SelectedItem.ToString();
string selectLocation = cbLocation.SelectedItem.ToString();
locationstation creLS = new locationstation();
creLS.idStation = cbStation.SelectedItem.ToString();
selectLocation.Location1 = (string)cbLocation.SelectedItem;
Setupctx.locationstations.AddObject(selectStation);
//Setupctx.SaveChanges();
//cbStation.SelectedIndex = -1;
//cbLocation.SelectedIndex = -1;
MessageBox.Show("New Location Station Is Created");
}
}
I don't how to make it working but my codes that i'm trying is right here. Help will be greatly appreciated.
This is the code that i bind the station name and location name into the combo box.
private void Create_LS_Load(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
var storeStation = (from SLS in Setupctx.locationstations
join station s in Setupctx.stations on SLS.idStation equals s.idstations
select s.Station1).Distinct().ToList();
foreach (var LocationStation in storeStation)
{
cbStation.Items.Add(LocationStation);
}
var storeLocation = (from SLS in Setupctx.locationstations
join location l in Setupctx.locations on SLS.idLocation equals l.idlocation
select l.Location1).Distinct().ToList();
foreach (var LocationStation1 in storeLocation)
{
cbLocation.Items.Add(LocationStation1);
}
}
}

Hi set all Navigation properties of selectStation equal to null before Adding the the object using
Setupctx.locationstations.AddObject(selectStation);
instead of
string selectStation = cbStation.SelectedItem.ToString();
use
LocationStation selectStation=(LocationStation)cbStation.SelectedItem;
and then extract values from selectStation or do what you want with it.
I hope this will help.

Station selectStation = (Station)cbStation.SelectedItem ; //cast here to your T
Location selectLocation = (Location)cbLocation.SelectedItem; //cast here to your T
locationstation creLS = new locationstation()
{
StationId=selectStation.Id ,
LocationId=selectLocation.Id
};
Setupctx.locationstations.AddObject(creLS);
Setupctx.SaveChanges();
However I can not imagine doing something like above on the combobox with Key/Value data.
because probably binding lookup types comboboxes to KeyValuePair by using .ToDictionary()
(where T is type of primary key) opens up easier code reuse to handle
selected items and bindings on any combobox in whole app by setting ValueMember = Key
and DisplayMember =Value (or whatever Key/Value properties are in your combo control) then you can do this for example:
long GetSelectedId(comboBox cbo)
{
long IdOut=-1;
if (cbo.SelectedItem==null)
return IdOut;
KeyValuePair<long, string> Item= (KeyValuePair<long, string>)cbo.SelectedItem;
IdOut = Item.Key;
return IdOut;
}

Related

How to add a dictionary to a ContextMenuStrip

I am currently trying to add to a context menu strip a dictionary of status values. The main issue I am having is how to pass in the Key value of the selected dictionary item to a click event.
Dictionary<int, string> statusList = getStatusList();
if (statusList.Count > 0)
{
Dictionary<int, ToolStripItem> statusMenu = new Dictionary<int, ToolStripItem>();
foreach (var keyValuePair in statusList)
{
statusMenu.Add(keyValuePair.Key, new ToolStripMenuItem() { Text = keyValuePair.Value.ToString(), Image = Resources.Refresh });
//statusMenu[statusMenu.Count - 1, statusMenu].Click += new EventHandler(MenuOption_Click_Handler); This is where I am confused
}
datagridview1.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Set Status to", Resources.Refresh, statusMenu.Values.ToArray()));
}
I can easily get the array of the dictionary values. I am just wondering if its possible upon clicking a status in the contextmenu to pass the Key to a save method?
So, for example say statusList contains the following values:
{[1, Status1]}
{[2, Status2]}
{[5, Status3]}
So if I load the contextmenu, if I click Status3, I need to pass to the ClickEvent that Status Key 5 was clicked. Right now its only detecting the Value (Status3). Any help is much appreciated!
Why don't you rename your tooltip control? The id is the key of Dictionary, so it should be distinct. Anyway, any control must have name.
This is an idea. You name the control with the prefix ToolStrip(or whatever you like) + Key and get it later. Like:
var newItem= new ToolStripMenuItem() {
Text = keyValuePair.Value.ToString(),
Image = Resources.Refresh,
Name="ToolStrip" + keyValuePair.Key };
newItem.Click +=new EventHandler(MenuOption_Click_Handler);
statusMenu.Add(keyValuePair.Key,newItem);
In MenuOption_Click_Handler method:
public void MenuOption_Click_Handler(object sender,EventArgs e)
{
var id = Convert.ToInt32(((ToolStripMenuItem)sender).Name.Substring(0,9));
}

How to delete row in SQLite via ListView in C# for Windows 8 app

Here is the code I am using. The item in ListView AllEventsList in table Events does not gets deleted.
private async void DeleteSelected(object sender, RoutedEventArgs e)
{
try
{
var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
using (var db = new SQLite.SQLiteConnection(dbpath))
{
db.Delete<Events>(AllEventsList.SelectedItem.ToString());//selected item
var d = from x in db.Table<Events>() select x;
AllEventsList.Items.Clear();
foreach (var sd in d)
{
AllEventsList.Items.Add(sd.EventName.ToString());
}
db.Dispose();
db.Close();
}
var line = new MessageDialog("Selected Item Deleted");
await line.ShowAsync();
}
catch
{
}
}
while this works:
db.DeleteAll<Events>();
Try this,
foreach ( ListViewItem eachItem in AllEventsList.SelectedItems)
{
AllEventsList.Items.Remove(eachItem);
}
I suspect it is the ToString not giving the value that you expect. Try explicitly passing the primary key value instead, such as:
var primaryKey = ((Events)AllEventsList.SelectedItem).YourPrimaryKeyId;
db.Delete<Events>(primaryKey);
or you could just call this version of Delete, and pass in the entire object:
db.Delete(AllEventsList.SelectedItem);
Some notes:
I did not do error condition handling in my code above. You will have to this. For example making sure that there actually is a selected item in the list, otherwise with the code above you will get a null reference exception.
your calls to Dispose and Close are redundant. You can remove those because you are already inside of a using block.

Dropdown List value not updated after changing selection

I'm using a dropdownlist which allows the user to choose a value (representing a client name.) I'm binding that list in the Page_Load doing it like that :
if(!IsPostBack)
{
var airClients = (from ac in db.AIR_CLIENTS orderby ac.CLIENT select ac.CLIENT).ToList();
ddlClients.DataSource = airClients;
ddlClients.DataBind();
}
If I'm reaching my Edit view (with all the fields filled, including that dropdownlist), I can change the client by selecting another one in the list. However, when I'm saving, the new selected value is not taken into account. I'm trying to get it by doing that :
protected void btnSave_Click(object sender, EventArgs e)
{
Entities db = new Entities();
if (Session["id"] != null)
{
int id = Convert.ToInt32(Session["id"].ToString());
SIMULATION simulation = (from s in db.SIMULATION where s.SIMULATION_ID == id select s).FirstOrDefault();
string client = ddlClients.SelectedItem.Text;
AIR_CLIENTS currentClient = (from ac in db.AIR_CLIENTS where ac.CLIENT == client select ac).FirstOrDefault();
int monthNego = Convert.ToInt32(ddlMonthNegotiation.SelectedItem.Text);
int roundNego = Convert.ToInt32(ddlRoundNegotiation.SelectedItem.Text);
simulation.SIMULATION_NAME = mmDesc.Text;
simulation.SIMULATION_TYPE = ddlSimulationType.SelectedItem.Text;
simulation.CLIENT_ID = currentClient.CLIENT_ID;
simulation.SIM_START_DATE = dteStart.Date;
simulation.SIM_END_DATE = dteEnd.Date;
simulation.CONTRACT_YEAR = ddlContractYear.SelectedItem.Text;
simulation.MONTH_OF_NEGOTIATION = monthNego;
simulation.ROUND_OF_NEGOTIATION = roundNego;
db.SaveChanges();
Response.Redirect("MainPage.aspx");
}
}
So in order to have a clear idea of what I want to say, if in my Edit View I've got "Apple" as the original value and I want to change it by selecting "Amazon", when I'm debugging I still see "Apple" as the selected value.
I can't figure out where I should fix the code to make it work. Any idea?
EDIT : ASPX dropdownlist code
<dx:ASPxComboBox runat="server" ID="ddlClients" ClientInstanceName="ddlClients"></dx:ASPxComboBox>
I'm using the DevExpress library but I think it isn't reliable.

How to get Combobox.Datasource to a Dictionary?

Following is my code which is binding a List() to a ComboBox control. I tried to add few items to the CombBox control using Insert() method which is not allowed as it has been assigned to a datasource. So, how can I get the datasouce back to a new variable (say, var colours2) from cmbColour.DataSource which is returning an object. Thanx !
var colours= new Dictionary<string, string>
{
{"1x","Green"},
{"2x","Red"},
{"3y","Blue"},
{"4y","Black"}
}.ToList();
cmbColour.ValueMember = "Key";
cmbColour.DisplayMember = "Value";
cmbColour.DataSource = colours;
var colours2 = //how can I get the DataSource back
The following code will return a new dictionary containing the same data you bound to the combo box.
var list = (List<KeyValuePair<String, String>>)cmbColor.DataSource;
var dictionary = list.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
The property DataSource will return the same instance you assigned but because it is typed Object you have to cast it back to the actual type before you can access any members.
But why don't you just keep the original dictionary? And it is definitely supported to modify a list bound to a data source - that is the whole point of data binding.
I guess my answer does not really solve your actual problem, only what you think what your problem is. Maybe you can give some additional information about what you are trying to achieve and I or someone else will be able to help you with your underlying problem.
UPDATE
This should work for your scenario - I stick with the user example.
public class User
{
public String Id { get; set; }
public String Name { get; set; }
}
And the code for the form.
public partial class MainForm : Form
{
private readonly BindingList<User> recentlyAddedUsers = new BindingList<User>();
private void MainFormLoad(Object sender, EventArgs e)
{
this.comboBoxRecentlyAddedUsers.DataSource = this.recentlyAddedUsers;
this.comboBoxRecentlyAddedUsers.ValueMember = "Id";
this.comboBoxRecentlyAddedUsers.DisplayMember = "Name";
var recentlyAddedUsersFromService = this.GetRecentlyAddedUsers();
foreach (var user in recentlyAddedUsersFromService)
{
this.recentlyAddedUsers.Add(user);
}
}
private void ButtonAddNewUserClick(Object sender, EventArgs e)
{
var newUser = new User();
newUser.Id = this.textBoxUserId.Text;
newUser.Name = this.textBoxUserName.Text;
this.SaveNewUser(newUser);
this.recentlyAddedUsers.RemoveAt(0);
this.recentlyAddedUsers.Insert(newUser);
}
private List<User> GetRecentlyAddedUsers()
{
// Get a list of recently added users from the database.
}
private void SaveNewUser(User user)
{
// Save the new user to the database.
}
}
Note the usage of BindingList<T> - this will notify the combo box about any changes to the list. A simple List<T> would also work but then you have to explicitly tell the combo box to refresh the data binding.
Since DataSource is typed as an object there's not a clean way to extract the data from it. If you know the underlying type of the data source (meaning you set it somewhere else so you KNOW what type it is) you can just cast it and add items to the collection.
Be aware that the object will be a REFERENCE not a COPY of the original object, meaning if you set the data source to a dictionary initially then try to extract it to add items you're adding items to the SAME dictionary.
So in your case:
var colours2 = cmbColour.DataSource as List<KeyValuePair<string, string>>;
// can add items to colours2 here (but it is the same instance as colours)
var coloursList = cmbColour.DataSource as List<KeyValuePair<string, string>>;
var colours2 = coloursList.ToDictionary(x => x.Key, x => x.Value);
You can get the data back by using following cast.
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var colours = new Dictionary<string, string>
{
{"1x", "Green"},
{"2x", "Red"},
{"3y", "Blue"},
{"4y", "Black"}
}.ToList();
cmbColour.DataSource = colours;
List<KeyValuePair<string, string>> l1 = new List<KeyValuePair<string, string>>();
l1 = (List<KeyValuePair<string, string>>)cmbColour.DataSource;
}
}
}
List<KeyValuePair<String, String>> c = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("m", "n"),
new KeyValuePair<string, string>("k", "c")
};
comboBox1.DataSource = c;
c.Add(new KeyValuePair<string, string>("new","new value"));
or
var list = (List<KeyValuePair<String, String>>)comboBox1.DataSource;
list.Add(new KeyValuePair<string, string>("new", "new value"));

Storing records in a dropdownlist from DB without using LINQ Data source

I have a website for dance academy where Users can register and add/drop dance classes.
In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances.
Now I want to delete one of the dances from the list.
So i'll remove the row from the table and also from the dropdownlist. The problem is that every time the item with the lowest ID (index) is getting deleted, no matter which one the user selects.
I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. Can someone please help me out?
The code is:
private void PopulateDanceDropDown()
{
var registereddanceList = from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Text = dd.DanceName,
Value = dd.DanceId
};
dances.DataSource = registereddanceList;
dances.DataTextField = "Text";
dances.DataValueField = "Value";
dances.DataBind();
}
protected void dropthedance(object o, EventArgs e)
{
String strDataValueField = dances.SelectedItem.Value;
int danceIDFromDropDown = Convert.ToInt32(strDataValueField);
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
PopulateDanceDropDown();
}
<asp:DropDownList ID = "dances" runat="server">
</asp:DropDownList>
<asp:Button ID="dropDance" runat="server" OnClick="dropthedance" Text="Drop Class" BackColor="Maroon" ForeColor="#FFCC99"/>
As your question says you want to access records without storing it in Linq.
So below one could be an alternative for you.
First store all the data from Database to, lets say List<NameIDPair>
Heres what NameIDPair could be:
class NameIDPair
{
public NameIDPair(){}
public string NameValue{get;set;}
public string IDValue{get;set;}
}
Then populate drop down list as follows:
List<NameIDPair> storeInMe = From Database
foreach(NameIDPair pair in storeInMe )
{
ListItem item = new ListItem();
item.Value = pair.IDValue;
item.Text = pair.NameValue;
ddldancesList.Items.Add(item);
}
Then for droppingTheDance, you can call the delete stored procedure to delete the same...
Hope this helps...

Categories