display details using entity framework - c#

I want to display details of a selected item from a combo box in wpf using entity framework. But my code below only displays the first entry from database no matter what item is selected.
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (Entities c = new Entities())
{
string sFirst = c.UserProfiles.FirstOrDefault().First.ToString();
string sLast = c.UserProfiles.FirstOrDefault().Last.ToString();
txtFirst.Text = sFirst;
txtSecond.Text = sLast;
}
}

I think you are mixing up stuffs.
I believe what you actually want is the item within the combox.
Try this code:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
var item = comboBox.SelectedItem as EntityType;
//EntityType == the table you are loading into combobox (I guess it supposed to be UserProfile)
if (item != null)
{
txtFirst.Text = item.First.ToString();
txtSecond.Text = item.Last.ToString();
}
}
}

You are not filtering the data from the database... there is no where clause that specifies the selected item. I have no idea on the structure of your data but try something like this:
using (Entities c = new Entities())
{
string sFirst = c.UserProfiles.Where(u => u.Id == selectedItemId).First().First.ToString();
string sLast = c.UserProfiles.Where(u => u.Id == selectedItemId).First().Last.ToString();
txtFirst.Text = sFirst;
txtSecond.Text = sLast;
}
Furthermore, there is no point in using FirstOrDefault() if you are not going to check whether the result is null or not.

Related

Populating textBoxes with

I'm designing a CheckOut page and I want to automatically load the signed in user's information with data from the database using linq. I'm using a method FillPage which I call in PageLoad and so far it looks like this:
void FillPage(int id)
{
using (DatabaseContext db=new DatabaseContext()
{
var query = (from user in db.[tblUser]
where user.ID == id
select user
).First();
if (query != null)
{
txtName.Text = query.Username;
txtEmail.Text = query.Email;
txtAddress.Text = query.PostalAddress;
ddProvice.SelectedValue = query.Province;
lblPassword.Text = query.Password;
lblDate.Text = query.DateRegistered.ToString();
}
}
}
Why does nothing happen when I load the page?
You must insert more of your code .your problem is not clear
May be in your load event of your page you forget to add
If (! IsPostback)
{
}
And may be you have reset your fields
public void MyPage_load( object sender , EventArgs e)
{
//Reset fields
}
This will fix your problem
public void MyPage_load( object sender , EventArgs e)
{
If (! IsPostback)
{
//Reset fields
}
}

How to edit databound combobox in c#

In my winForm application I have added databound combobox column in a datagridview. User needs to be able to select an item from dropdown list or write in the combobox. But it wouldn't let me write in the combobox as datasource is set. This is my code:
var entityModel= new AdminEntities();
var filterPractice = (from b in entityModel.FILTER where b.PRACTICE != null select b.PRACTICE).Distinct().OrderBy(y => y);
dgvCboColumn(filterPractice, "PRACTICE");
private void dgvCboColumn(dynamic item, string colName)
{
int i = dgvLoadTable.Columns[colName].Index;
DataGridViewComboBoxColumn dgvCol = new DataGridViewComboBoxColumn();
dgvCol.DataSource=item;
dgvCol.DataPropertyName = colName;
dgvLoadTable.Columns.Insert(i, dgvCol);
dgvLoadTable.Columns[i].HeaderText = dgvLoadTable.Columns[i + 1].HeaderText;
dgvLoadTable.Columns[i + 1].Visible = false;
dgvLoadTable.Columns.RemoveAt(i + 1);
}
private void HandleEditShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var cbo = e.Control as ComboBox;
if (cbo == null)
{
return;
}
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.Validating -= HandleComboBoxValidating;
cbo.Validating += HandleComboBoxValidating;
}
private void HandleComboBoxValidating(object sender, CancelEventArgs e)
{
var combo = sender as DataGridViewComboBoxEditingControl;
if (combo == null)
{
return;
}
if (!combo.Items.Contains(combo.Text))
{
var comboColumn = this.dgvLoadTable.Columns[this.dgvLoadTable.CurrentCell.ColumnIndex] as DataGridViewComboBoxColumn;
combo.Items.Add(combo.Text);
comboColumn.Items.Add(combo.Text);
this.dgvLoadTable.CurrentCell.Value = combo.Text;
}
}
Can anyone tell me how can I make the combobox editable, please?
you can manually get the items frm datasource using Oledb or Ado recordset nd fill de comboBox manually by using for loops.. so basically you can also edit the items..

Show an error on a label box for invalid username or password

This is my code. How to write the code label box. I am selecting data from two different table for each table it ll redirect to two different pages.
protected void Button1_Click(object sender, EventArgs e)
{
var qry = (from test in je.employee
where test.emp_email.Equals(TxtUserName.Text) &
test.emp_pass.Equals(TxtPassword.Text)
select test).FirstOrDefault();
if (null != qry)
{
Response.Redirect("EmployeeHome.aspx");
}
else
{
var qry2 = (from test1 in je.employer
where test1.c_mail.Equals(TxtUserName.Text) &
test1.c_pass.Equals(TxtPassword.Text)
select test1).FirstOrDefault();
if (null != qry2)
{
Response.Redirect("EmployerHome.aspx");
}
}
}
Try this:
var qry = (from test in je.employee
where test.emp_email.Equals(TxtUserName.Text) & test.emp_pass.Equals(TxtPassword.Text)
select test).FirstOrDefault();
var qry2 = (from test1 in je.employer
where test1.c_mail.Equals(TxtUserName.Text) & test1.c_pass.Equals(TxtPassword.Text)
select test1).FirstOrDefault();
if (null!=qry)
{
Response.Redirect("EmployeeHome.aspx");
}
else if(null != qry2)
{
Response.Redirect("EmployerHome.aspx");
}
else
{
Label1.Text = "Incorrect username or password!";
}

LongListSelector.SelectedItem can't cast to my object class

I have a LongListSelector that is populated with List which contains objects from SQLite database:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(DB_PATH);
var query = conn.Table<Prasanja>().Where(x => x.id == 3);
var result = await query.ToListAsync();
foreach (var item in result)
{
var query1 = conn.Table<Odgovori>()
.Where(y => y.Prasanja_id == item.id);
txtPrasanje.Text = item.Tekst;
var resultOdgovori = await query1.ToListAsync();
foreach (var itemOdgovor in resultOdgovori)
{
Lista.Add(itemOdgovor.Odgovor.ToString());
lstOdgovori.ItemsSource = Lista;
}
}
What I want is when one of the LongListSelector items is tapped that I get the specific object tapped, and have the ability to use that object properties.Here is my code:
private void lstOdgovori_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
if (selector == null)
return;
Odgovori odg = selector.SelectedItem as Odgovori;
if (odg == null)
return;
if(odg.Tocno==null)
MessageBox.Show("Try again");
else MessageBox.Show("True!!!");
}
The problem here is that my object odg from the class Odgovori returns null after executing this code. How can I fix this?
You are adding a string to Lista that is why your casting is not working. If you have overridden your ToString() method in your Odgovori class I believe that the LongListSelector will call that method if you just add the Odgovori object to Lista

Access columns in ItemDataBound event when the datasource is Linq

Im setting the the datasource with the following code:
protected void Page_Load(object sender, EventArgs e)
{
var vacancies = from v in db.Vacancies
join c in db.Customers on v.CustomerID equals c.CustomerID
join cp in db.CustomerPortals on c.CustomerID equals cp.CustomerID
where cp.PortalID == Master.Portal.ID
select new
{
Title = v.Title,
Internship = (v.ContractID == 6),
Hours = v.Hours,
City = v.Customer.City.Name,
Degree = v.Degree.Title,
Contract = v.Contract.Title,
CustomerID = v.CustomerID
};
rVacancies.ItemDataBound += new RepeaterItemEventHandler(rVacancies_ItemDataBound);
rVacancies.DataSource = vacancies;
rVacancies.DataBind();
}
Now i want to know how i can access 1 of the columns (like CustomerID) from the ItemDataBound event.
void rVacancies_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// This doesnt seem to work, row would be null even though e.Item.DataItem has a value.
DataRow row = (DataRow)e.Item.DataItem;
}
I have figured out that e.Item.DataItem contains all the fields from my query and the type of e.Item.DataItem is
f__AnonymousType8<string,bool,byte,string,string,string,long>
Finally found it, was as simple as the following:
long customerID = long.Parse(DataBinder.Eval(e.Item.DataItem, "CustomerID").ToString());
This .Net 4.0 approach is also very cool indeed!
public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
dynamic person = e.Item.DataItem as dynamic;
string name = person.Name;
int age = person.Age;
}
}
All Credit To:
http://www.kristofclaes.be/blog/2010/08/12/anonymous-types-and-the-itemdatabound-event/
Because the page now shows an Error 404, here is the page from the Wayback Machine:
Anonymous types and the ItemDataBound event (Archived version)
You're not binding a datarow to your control (you're binding an anonymous type), so you should not cast DataItem to DataRow.
Try to get your row's data as :
var dataItem = e.Item.DataItem;
// For example get your CustomerID as you defined at your anonymous type :
string customerId = dataItem.CustomerID;

Categories