I have a gridview, bound to a datasource whose database table contains a foreign key that is associated with the database table that is used as the datasource for a dropdownlist.
What I want to do is if a certain foreignKeyId exists in gridview.datasource, to remove it from dropdownlist.datasource.
To give a clearer idea of what/why I want what I want, the user is able to add entries to the gridview (and therefore the datasource), but I don't want the user to be able to make more than one entry for a specific type. Is there a way that a linq query could do this?
pseudocode (note that I know RemoveObjects() is an invalid method)
var query = DataContext.Items.Where(item => item.TypeId == selectedTypeId);
dropDownList.DataSource.RemoveObjects(query);
Here is how I bind the dropdownlist, so maybe I could do something here to not get the items with already existing TypeId's?
dropDownList.DataSource = DataContext.Items.Select(items => new
{
items.Name,
items.TypeId,
}).ToList();
Any suggestions or answers would be great!
Have you tried using except
dropDownList.DataSource.Except(query)
Related
I have to implement a function to sort the data displayed in frontend table. There the user can click the up and down arrow in the relevant column he wants to sort. then all the data in all the columns should be sorted according to that relevant column user clicked. How can i do this in c# with mongodb.
I have wrote this to sort according to the date (one column in the table. There are so many others like name, id etc.)
result = await _mongoDb.GetCollection<Entity.Mongo.MyModelClassName>(MyCollectionName)
.Sort(Builder<Entity.Mongo.MyModelClassName>.Sort.Ascending(x => x.Date))
this is working fine.
But what i need now is to remove this hard coded one and sort according to the user preference.
Can someone help me with this?
You should do a simple query and according to the sortOrder selected by the user, server-side you execute the sorting.
This should help you understand this concept : https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
So,
In the URL, you should have a parameter for the sortOrder.
In the OnGet() execute your query and then the sorting on this collection based on this parameter.
Then you should have a sorted collection and be able to do what you want to do.
I have 4 Dropdown and i am using one Database table for binding Dropdown. But in Dropdown i am getting duplicate values. I used Distinct in select statement but i amnot gettng unique value because it has 4 column.
So is there any way to get unique values or anyway to not getting duplicate value.
If
there are 4 columns
you applied DISTINCT
how did you manage to get duplicates? What duplicates? DISTINCT removes them, so there shouldn't be any rows where those 4 values match.
A blind guess: if you want to get distinct values for one of those columns and don't care about the rest of them, then something like this might help:
select
id, --> this is that "unique" value you're looking for
max(name), --> use one of aggregates for the rest of columns, ...
max(address), --> ... such as MAX in my example
max(phone)
from your_table
group by id --> as aggregates require GROUP BY, you don't need DISTINCT
If it still doesn't help, I'm afraid you'll have to explain the problem better. Don't forget to provide test case.
Distinct() needs to know how to tell if an item in your collection matches another item.
Try something like this.
items.Distinct((itemA, itemB) => string.Equals(
itemA.Name, itemB.Name, StringComparison.InvariantCultureIgnoreCase())
Check your Binding. You should bind only
if(!IsPostBack)
{
//Put the logic for the Dropdown DataBind here
}
If you don't do this you get a new set of Dropdown values with each postback and that's how you got the duplicate values.
If it is not the Binding could you post your SQL statement?
I have a drop down list which retrieves values from a session I declare as follows.
var autoData = autoRetriever.GetAutoDataByUserId(user.Id);
Session["AutoData"] = autoData;
I then use autoData to populate my drop down list with a “Name” and a int “Value” as indexed in the database. Name and value are both part of my table in the database.
What I am trying to do now is once a user selects from the drop down I am passing the value (e.g 0,1,2,3,n) the id on the db table to a method. OnSelected changed I want to use this value and retrieve another column “Path” from my session (autoData). Namely the path that is associated with the id. Once I have the correct “Path” associated with this value I can move forward with it.
With my OnSelectedIndexChanged method I then have the following. This string selectedAuto contains my value (0,1,2,3,n)
string selectedAuto = AutoDropDown.SelectedValue;
Does anyone have any advice on how I could move forward with this? If I have not explained enough please let me know and I will delve deeper into it.
As #David mentioned yes correct i am trying to use that value to identify that record. That is the part i am finding tricky. How can i retrieve that "Path" based on the value i select.
I am Working in C# winform to load values for a combobox from a datatable with some filter query. Following is the code sample,
repeatCombobox.Items.AddRange(dataTable.Select(myFilterStrin));
repeatCombobox.DisplayMember = "EnumerationText";
repeatCombobox.ValueMember = "Value";
But the problem here is, records selected from the table are 'ordered by value in ascending manner' by default in the combobox.
I would like to load items as it is in the table (no order) rather than any ordering of value either ascending or desending..... but could not do it till now. Can anybody help me out on this?
try
repeatCombobox.Sorted = false;
Edit: if problem is not caused by the combobox's Sorted property, it's probably caused by the missing (or non-incremental) primary key in your database table. DataTable.Select sorts by the primary key by default. If you are not able to add/change the primary key, then you may try adding a new column which has incremental values (maybe you can create a view as well) and use a second parameter in select like dataTable.Select(myFilterStrin, "SortIndex Asc");
In my DataGridView I'am displaying a buch of columns from one table. In this table I have a column which points to item in another table. As you may already guessed, I want to display in the grid in one column some text value from the second table instead of and ItemID.
I could not find a right example on the net how to do this.
Lets assume that I have two tables in databes:
Table Users:
UserID UserName UserWorkplaceID
1 Martin 1
2 John 1
3 Susannah 2
4 Jack 3
Table Workplaces:
WorkplaceID WorkplaceName
1 "Factory"
2 "Grocery"
3 "Airport"
I have one untyped dataset dsUsers, one binding source bsUsers, and two DataAdapters for filling dataset (daUsers, daWorkplaces).
Code which I am performing:
daUsers.Fill(dsUsers);
daWorkplaces.Fill(dsUsers);
bsUsers.DataSource = dsUsers.Tables[0];
dgvUsers.DataSource = bsUsers;
At this point I see in my dgvUsers three columns, UserID, UserName and UserWorkplaceID. However, instead of UserWorkplaceID and values 1,2,3 I would like to see "Factory", "Grocery" and so on...
So I've added another column to dgvUsers called "WorkplaceName" and in my code I am trying to bind it to the newly created relation:
dsUsers.Relations.Add("UsersWorkplaces", dsUsers.Tables[1].Columns["WorkplaceID"], dsUsers.Tables[0].Columns["UserWorkplaceID"]);
WorkplaceName.DataPropertyName = "UsersWorkplaces.WorkplaceName";
Unfortunately that doesn't work. Relation is created without errors but fields in this column are empty after running the program.
What I am doing wrong?
I would like to also ask about an example with LookUp combobox in DataGridView which allow me to change the UserWorkplaceID but instead of numeric value it will show a tex value which is under WorkplaceName.
Thanks for your time.
In my opinion, the best decision would be to use the DataGridViewComboBoxColumn column type. If you do it, you should create a data adapter with lookup data beforehand and then set DataSource, DataPropertyName, DisplayMember, and ValueMember properties of the DataGridViewComboBoxColumn. You could also set the DisplayStyle property to Nothing to make the column look like a common data column. That's it.
I don't know if you can do exactly what you want, which seems to be binding the DataGridView to two different DataTable instances simulataneously. I don't think the DataGridView class supports that -- or if it does it's a ninja-style move I haven't seen.
Per MSDN, your best bet is probably using the CellFormatting event on the DataGridView and check for when the cell being formatted is in the lookup column, then you could substitute your value from the other table. Use an unbound column for the WorkplaceName column, hide the UserWorkplaceID column and then implement the CellFormatting event handle to look up the value in the row, e.g.:
private void dgv_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].Name.Equals("WorkplaceName")
{
// Use helper method to get the string from lookup table
e.Value = GetWorkplaceNameLookupValue(
dataGridViewScanDetails.Rows[e.RowIndex].Cells["UserWorkplaceID"].Value);
}
}
If you've got a lot of rows visible, this might impact performance but is probably a decent way to get it working.
If this doesn't appeal to you, maybe use the DataTable.Merge() method to merge your lookup table into your main table. A quick glance at one of my ADO.NET books suggests this should work, although I have not tried it. But I'm not sure if this is too close to the idea suggested previously which you shot down.
As for your second question about the lookup combobox, you should really post it in a separate question so it gets proper attention.
You could make SQL do the job instead. Use a join to return a table with Workplace names instead of IDs, output that table into a dataset and use it instead.
eg.
SELECT A.UserID, A.UserName, B.WorkplaceID
FROM Users A
JOIN Workplaces B ON A.UserWorkplaceID = B.WorkplaceID
Then use its output to fill dsUsers.