I have 2 tables in a database. One is with Users and and another one with Societies. Something like this:
Users table: Societies table:
ID User Pass ID UserID Societies
1 Mark 123 1 1 Pepsi
2 John abc 2 1 Lays
3 Paul a1b 3 2 Unilever
4 3 Nestle
UserID have a foreign key to ID from Users table.
And 2 forms: A Login panel for users and one to show in a Datagridview societies.
Now, I try to figure it out, when I'm logging in with a user, to show only Societies with the specific UserID for that user.
I made this method in Second Form to show specific societies, but I don't know what to put in Equals brackets. I tried a lot of possibilities, but nothing worked...
private void btnLoad_Click(object sender, EventArgs e)
{
DCApp db = DCApp.NewDC();
User logedUser = db.Users.FirstOrDefault(s => s == Program._us);
List<Society> ListSociety = db.Societies.Where(s => s.UserID.Equals(logedUser)).ToList();
_bs.DataSource = ListSociety;
dgwUser.DataSource = _bs;
dgwUser.Refresh();
_bs.ResetBindings(false);
}
If you have some tips, please, give me a path.
Rest of my code:
Program.cs
using System;
using System.Windows.Forms;
namespace Users
{
static class Program
{
public static User _us;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
frmLogin f = new frmLogin();
if (f.Run(out _us))
{
Application.Run(new frmUsers());
}
else
{
Application.Exit();
}
}
}
}
frmLogin.cs
namespace Users
{
public partial class frmLogin : Form
{
bool _Result = false;
User _user;
public frmLogin()
{
InitializeComponent();
}
internal bool Run(out User us)
{
us = _user;
ShowDialog();
return _Result;
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (cmdPassword.Text.Length == 0 || cmdUser.Text.Length == 0)
{
errH.SetError(btnLogin, "!");
return;
}
using (DCApp db = DCApp.NewDC())
{
List<User> logInP = db.Users.Where(s => s.UserPassword.ToLower().Equals(cmdPassword.Text.ToLower().Trim()) && s.UserName.ToLower().Equals(cmdUser.Text.ToLower())).ToList();
if (logInP.Count == 0)
{
_Result = false;
}
else if (logInP.Count > 1)
{
_Result = false;
}
else
{
_Result = (bool) logInP.FirstOrDefault().IsActive;
_user = logInP.First();
}
}
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
frmUsers.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace Users
{
public partial class frmUsers : Form
{
BindingSource _bs = new BindingSource();
public frmUsers()
{
InitializeComponent();
InitControls();
}
private void InitControls()
{
dgwUser.AutoGenerateColumns = false;
}
private void btnLoad_Click(object sender, EventArgs e)
{
DCApp db = DCApp.NewDC();
User logedUser = db.Users.FirstOrDefault(s => s == Program._us);
List<Society> ListSociety = db.Societies.Where(s => s.UserID.Equals(logedUser)).ToList();
_bs.DataSource = ListSociety;
dgwUser.DataSource = _bs;
dgwUser.Refresh();
_bs.ResetBindings(false);
}
}
}