Unable to get search result in the list. c# WPF - c#

private void SearchButton_Click(object sender, RoutedEventArgs e)
{
EmployeeDataDataContext con = new EmployeeDataDataContext();
List<Employee> employees = (from s in con.Employees
where s.Name.ToLower() == SearchBox.Text.ToLower()
select s).ToList();
EmployeeGrid.ItemsSource = employees;
}
private void Edit_Click(object sender, RoutedEventArgs e)
{
Employee selected = EmployeeGrid.SelectedItem as Employee;
if (selected == null)
MessageBox.Show("You must select the employee.");
else
{
EditEmployee employee = new EditEmployee(selected);
employee.ShowDialog();
}
}
could not getting anything in the list wheni press the search button .

It sounds like you want to do an partial match. You can use string.Contains for that
where s.Name.ToLower().Contains(SearchBox.Text.ToLower())
That will allow your text to match anywhere within the name column.

Related

Filtering datagridview with multiple combobox

I am trying to make a simple product code search using a datagridview.
I am able to filter the database but not able to get all the functions I want
I currently have it set as
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}'",
comboBox1.SelectedItem.ToString());
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
productsBindingSource.Filter = string.Format("Type = '{0}' AND Fitting = '{1}'",
comboBox1.SelectedItem.ToString(),
comboBox2.SelectedItem.ToString());
}
This code works but after the selections are made and I change comboBox1 the data resets and doesn't keep the selection of comboBox2.
I understand in my current code that this would not happen but I cannot figure out how to get this to happen.
I would also like to add a text box in the future and have it narrow the filter even more.
You should approach this a bit more generically like so
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
FilterProducts();
}
// Create a function to handle filters
private void FilterProducts()
{
string filter = "";
if (comboBox1.SelectedItem != null)
{
filter += string.Format("Type = '{0}'", comboBox1.SelectedItem.ToString());
}
if (comboBox2.SelectedItem != null)
{
if (filter.length > 0) filter += "AND "
filter += string.Format("Fitting = '{0}'", comboBox2.SelectedItem.ToString());
}
// Add another like above for your future textbox
// if (!string.IsNullOrEmpty(textBox1.Text))
// {
// if (filter.length > 0) filter += "AND "
// filter += string.Format("OtherColumn = '{0}'", textBox1.Text);
// }
productsBindingSource.Filter = filter;
}
The code could be further refactored for even better DRY standards but this should at least get you started.

How To Delete Multiple Items from ListView C# With Delete Button

So, I have a simple ListView that users can add information to and a delete button that is only capable of deleting one selected item at a time. I'm trying to make it so that when multiple items are selected and 'delete' is pressed it deletes those selected items instead of just one. Your help is appreciated!
Add recipient code:
private void addtoRecipients_Click(object sender, EventArgs e)
{
if (recipientEmailBox.Text != "")
{
string[] S = new string[4];
S[0] = recipientEmailBox.Text;
S[1] = recipientNameBox.Text;
S[2] = txtLocation.Text;
S[3] = txtSubject.Text;
ListViewItem I = new ListViewItem(S);
recipientBox.Items.Add(I);
UpdateNoOfEmails();
}
}
My Delete Button Code (only deletes one selection at the moment)
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try { recipientBox.Items.Remove(recipientBox.SelectedItems[0]); }
catch { }
UpdateNoOfEmails();
}
Clear All Recipients Code
private void clearBTN_Click(object sender, EventArgs e)
{
recipientBox.Items.Clear();
UpdateNoOfEmails();
}
In my case, the simplest way to do it was with a while loop. This is what my new delete button code looks like:
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try
{
while (recipientBox.SelectedItems.Count > 0)
{
recipientBox.Items.Remove(recipientBox.SelectedItems[0]);
}
}
catch { }
UpdateNoOfEmails();
}

How to save a page state?

In a Windows Runtime app, I load data like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
then user can select an item from ListView:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
So it navigates forward to the same page, but shows new followers.
The problem is that when it navigates back, it loads data again and shows from the beginning of the list rather than showing the last item selected.
So how to save a List of data in NavigationHelper_SaveState and how to load it again in NavigationHelper_LoadState with last position in the list? thanks.
Here's a basic semi-tested example you can start from. You'll need to modify it to fit your exact circumstances. Some of it is adapted from here.
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}

How to check a condition only once on datalist DataList.ItemDataBound Event

I have a Datalist that has a delete button in it , I want to check if the user is admin, shows this button for each item and if not dont show that. This is my ItemDataBound, my problem is that for each item it connects to database and check if user is admin or not and I am worried about getting slow for large number of items. How can I fix this problem?
protected void GroupMembersDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton deletButton = (LinkButton)e.Item.FindControl("DeletFromGroup");
// here first connecet to database to get group name
int GroupID = BusinessLayer.Group_Table.GetByUniqName(Page.RouteData.Values["GroupName"].ToString());
// here connect to database and find groups admin ID and checks that are the same or not ?
BusinessLayer.Group_Table GObject = new BusinessLayer.Group_Table(GroupID);
if (Convert.ToInt32(Session["ID"].ToString()) == GObject.Id)
{
deletButton.Visible = true;
}
else
{
deletButton.Visible = false;
}
}
}
Edit solution:
private BusinessLayer.Group_Table GObject;
private int GroupID;
protected void Page_Load(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(Session["ID"].ToString());
GroupID = BusinessLayer.Group_Table.GetByUniqName(Page.RouteData.Values["GroupName"].ToString());
GObject = new BusinessLayer.Group_Table(GroupID);
}
catch( Exception ee )
{
Response.Redirect("~/Home.aspx");
}
if (!IsPostBack)
{
getdata();
}
}
You could initialize a field in the class in Page_Load or the DataList's DataBinding event. Then you can access this field from ÌtemDataBound.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int GroupID = BusinessLayer.Group_Table.GetByUniqName(Page.RouteData.Values["GroupName"].ToString());
GObject = new BusinessLayer.Group_Table(GroupID);
DataBindDataList(); // code that calls DataBind
}
}
private BusinessLayer.Group_Table GObject;
Another way is to store this value in the Session.

Drop Down List make list item requery entitydatasource

My first post here and Iam an absolute beginner. Searched the web for hours. I feel that I might have approached my problem the wrong way, but here goes.
I have a Datasource that displays Loans (assets) in a Gridview.
I would like to have a ddl to filter loans. Like: `If returneddate !=null the items in grid will be free for a new loan.
Selecting ex. "Available assets" in ddl runs a where query on entitydatasource and retrieves the filtered data into grid.
My code: A bit of a mess, several queries that hopefully do the same. I prefer the first one LinqtoEntities
namespace Logsys.Pages
{
public partial class OversiktLån : Page
{
private LogsysEntities context = new LogsysEntities();
protected void Page_Load(object sender, EventArgs e)
{
}
protected EntityDataSource LaanLedig(object sender, EventArgs e)
{
var ledigQuery = from laan in context.Laans
where laan.Returnertdato != null
select laan;
foreach (var laan in ledigQuery)
{
}
}
protected void DDLlaan_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void LaanEntityDataSource_QueryCreated(object sender, QueryCreatedEventArgs e)
{
var laanQuery1 = e.Query.OfType<Laan>();
e.Query = from c in laanQuery1
where (c.Returnertdato != null)
select c;
How to get result of query "into" datasource and make ddl items trigger queries?
KK
protected void ddlLaan_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 ddlvalue = Convert.ToInt32(ddlLaan.SelectedValue);
if (ddlvalue == 1)
{
CLogsysEntities = new LogsysEntities();
var ledig =
from laan in CLogsysEntities.Laans
where laan.Returnertdato != null
select laan;
LaanGridView.DataSourceID = null;
LaanGridView.DataSource = ledig.ToList();
LaanGridView.DataBind();

Categories