I have a DataGridView which I want to fill from my database. I got an empty DataGridView. Here's my script and what I tried :
private void listUser_Load(object sender, EventArgs e)
{
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers;
}
My class :
class User
{
private int id { get; set; }
private int level { get; set; }
private string name { get; set; }
private string password { get; set; }
private string email { get; set; }
public User(int idP, int levelP, string nameP, string passwordP, string emailP)
{
id = idP;
level = levelP;
name = nameP;
password = passwordP;
email = emailP;
}
}
And the way I got my data :
public static List<User> getUsers()
{
MySqlDataReader result = executerSelect("SELECT id, level, name, email, password FROM users");
List<User> users = new List<User>();
if(result != null)
{
while(result.Read())
{
int id = int.Parse(result[0].ToString());
int level = int.Parse(result[1].ToString());
string name = result[2].ToString();
string email = result[3].ToString();
string password = result[4].ToString();
users.Add(new User(id, level, name, password, email));
}
}
return (users.ToList());
}
I already tried with a binding source but I'm not able to link with my datagridview
Thanks for help
You need to assign lesUsers , instead of getUsers which is a method
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers ;
EDIT
check if you have public properties which would be used to display the contents of the Class as columns in the DataGridView
Related
I have two related classes:
public class Dealer {
public int Id { get; set; }
public string BaseUrl { get; set; }
public virtual ICollection<DealerAddress> DealerAddress { get; set; }
}
public class DealerAddress {
public int Id { get; set; }
public int DealerId { get; set; }
public string Email { get; set; }
public virtual Dealer Dealer { get; set; }
}
And in my form I want to display data from DealerAddress class:
public SortableBindingList<DealerAddress> Addresses = new SortableBindingList<DealerAddress>();
private void CreateDataGridView() {
dataGridViewPlaceHolderPanel.Visible = false;
dataGridView = new DataGridView();
dataGridView.Name = "dataGridView";
List<string> regularColumns = new List<string>()
{
nameof(DealerAddress.Id),
nameof(DealerAddress.DealerId),
nameof(DealerAddress.Dealer.BaseUrl),
nameof(DealerAddress.Email),
};
var columns = new List<DataGridViewTextBoxColumn>();
foreach (var regularColumnName in regularColumns)
{
var col = new DataGridViewTextBoxColumn
{
HeaderText = regularColumnName,
DataPropertyName = regularColumnName,
Name = "column" + regularColumnName
};
columns.Add(col);
}
}
public void SetAddresses(SortableBindingList<DealerAddress> addresses, int totalCount)
{
try
{
dataGridView.RowStateChanged -= DataGridView_RowStateChanged;
Addresses = addresses;
RefreshDataGridView();
}
finally
{
dataGridView.RowStateChanged += DataGridView_RowStateChanged;
}
}
private void RefreshDataGridView(){
if (Addresses == null || Addresses.Count == 0)
return;
dataGridView.DataSource = Addresses;
}
And the data displayed in my table is:
When I hit "SetAddresses", the data is populated from DealerAddress model, but it doesn't display column values from "DealerAddress.Dealer".
TL;DR
Quick fix it with the following. In your DealerAddres, add
public string BaseUrl
{
get => Dealer.BaseUrl;
set => Dealer.BaseUrl = value;
}
Explaining
You have two class DealerAddress and Dealer. You set a list of DealerAddress to the DataSource.
So when the DataGridView starts to render, it will search the properties in the first class.
When you do nameof(DealerAddress.Dealer.BaseUrl) you are actually telling, to the DataGridView, that the class DealerAddress contains that property --- which it does not.
See this for more information.
Noob question! Need some help!
So I'm using GoogleSheets API to store user credentials.
I created a custom list with all the data of every user in the GoogleSheet, I need to verify if the data inserted by user matches something within the list.
I managed to check if the username matches, but how to check if the password matches that username?
##The class
public class ListadeJogadoresRegistados
{
public int id { get; set; }
public string nome { get; set; }
public string pwd { get; set; }
public int hiscore { get; set; }
}
##Building the list
private static List<ListadeJogadoresRegistados> GetListaJogadores()
{
var request = service.Spreadsheets.Values.Get(SpreadsheetID, range);
var response = request.Execute();
var values = response.Values;
var jogador = new List<ListadeJogadoresRegistados>();
foreach (var row in values)
{
jogador.Add(new ListadeJogadoresRegistados
{
id = Int32.Parse((string)row[0]),
nome = (string)row[1],
pwd = (string)row[2],
hiscore = Int32.Parse((string)row[3])
});
}
return jogador;
}
##Data validation
public static bool ValidarLogin(string username, string pwd)
{
var jogadores = GetListaJogadores();
ListadeJogadoresRegistados item = jogadores.Find(item => item.nome == username && item.pwd == pwd);
if (item != null) // check item isn't null
{
// it is logged in
}
return true;
I am trying to get all data from DB and display it in a table using ajax and stored procedure.
public List<string> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<string> users = new List<string>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User();
user.userId = dataReader[1] as string;
user.password = dataReader[2] as string;
user.userName = dataReader[3] as string;
user.address = dataReader[4] as string;
user.email = dataReader[5] as string;
user.phone = dataReader[6] as string;
//here I want to assign each object property as list element
}
return users;
}
}
Below are two ways to generate a list of strings from the properties of a User instance.
internal class User
{
public string userId { get; set; }
public string password { get; set; }
public string userName { get; set; }
public string address { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string[] GetProperties()
{
return new string[]
{
userId,
password,
userName,
address,
email,
phone
};
}
static PropertyInfo[] properties = typeof(User).GetProperties();
public string[] GetPropertiesAuto()
{
return properties.Select((prop) => prop.GetValue(this) as string).ToArray();
}
}
The above can be used in your code quite simply, although you have to return a list of string array to get all the properties for all the users.
static public List<string[]> ShowDetailsFromDB()
{
using (var adoHelper = new AdoHelper(connectionString))
{
List<string[]> users = new List<string[]>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
var user = new User
{
userId = dataReader[1] as string,
password = dataReader[2] as string,
userName = dataReader[3] as string,
address = dataReader[4] as string,
email = dataReader[5] as string,
phone = dataReader[6] as string
};
//here I want to assign each object property as list element
users.Add(user.GetPropertiesAuto());
}
return users;
}
}
You can do it easy using a List of Users.
public class User
{
public string userId { get; set; }
}
public List<User> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<User> users = new List<User>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User
{
userId = dataReader[1] as string
};
users.Add(user);
//here I want to assign each object property as list element
}
return users;
}
}
Please tell me if it works
I have models as follows:
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Truck { get; set; }
public bool Car { get; set; }
public bool Bus { get; set; }
}
public class TransportDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Url{ get; set; }
}
I also defined a list that contains user details as follows:
public List<UserDetails> GetAllUserDetails()
{
List<UserDetails> userDetails = new List<UserDetails>
{
new UserDetails
{
Id = 1,
Username = "admin",
Password = "123",
Truck = false,
Car = true,
Bus = true
},
new UserDetails
{
Id = 2,
Username = "superadmin",
Password = "123",
Truck = true,
Car = false,
Bus = true
}
};
return userDetails;
}
The app works as follows :
The user logins with a credentials.
Based on his credentials, it is determined which property he has access to, either truck, car or bus. And he is directed to the MainPage.
When redirected to the MainPage, buttons should appear with the properties' values that the user has access to.
In other words, the buttons should have name as defined in the Model TransportDetails
So far, this has been done:
public void CheckLogin()
{
UserData userData = new UserData();
allUsers = new List<UserDetails>();
allUsers = userData.GetAllUserDetails();
if (allUsers.Any(x => x.Username.Equals(Username) && x.Password.Equals(Password)))
{
var user = allUsers.Where(x => x.Username.Equals(Username) && x.Password.Equals(Password)).First();
Application.Current.MainPage.Navigation.PushAsync(new PortalPage(user));
}
else
{
Application.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "OK");
}
}
I want to get buttons to appeared dynamically based on what property is true in the model UserDetails once a user has logged in. Then, when the buttons appeared based on what is true for this user, I want the button name and button value (url) from the TransportDetails model.
Could someone advise me on how to achieve this please ?
StackLayout stack = new StackLayout();
if (user.Truck) {
Button truck = new Button();
var transport = transports.Where(t => t.Name == "truck").First();
truck.Text = transport.Name;
truck.Clicked += (sender, e) => { Device.OpenUrl(transport.Url); };
stack.Children.Add(truck);
}
// repeat for other types
if you modify your UserDetails class
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public List<TransportDetail> Transport { get; set; }
}
then you could just do this
StackLayout stack = new StackLayout();
foreach (var t in user.Transport) {
Button btn = new Button();
btn.Text = t.Name;
btn.Clicked += (sender, e) => { Device.OpenUrl(t.Url); };
stack.Children.Add(btn);
}
I think you should modify your Model.
For every User you should have a ObservableCollection<TransportDetail> transportDetail
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
ObservableCollection<TransportDetails> TransportDetails{get;set;}
}
then you should add to TransportDetails only transport enabled to the user.
At this point, I suggest to use a ListView. On every ViewCell you should have a Button. Bind your properties to this Button. Fill the ViewCell with trasportDetail List
I have two pages. The first page is a registration page where the user creates a user name and password. The second page is a log in page, where the user enters their user name and password. I want to validate that the two match, on the front-end. I stored the user name and password in a session and am not using a database. This isn't working and I'm unsure why:
protected void Button1_Click(object sender, EventArgs e)
{
List<Information> downloadList = (List<Information>)Session["DownloadList"];
foreach (Information obj1 in downloadList)
{
newName = String.Format("{0}", obj1.name);
newPassword = String.Format("{0}", obj1.email);
}
if(newName != TextBoxUserNameMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct User Name";
}
else if(newPassword != TextBoxPasswordMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct Password";
}
else
{
Response.Redirect("DownloadPage.aspx");
}
}
Can anyone tell me where I'm going wrong here? Here is the class information:
public class Information
{
public String name { get; set; }
public String email { get; set; }
public String phone { get; set; }
public String zip { get; set; }
public String state { get; set; }
public String login { get; set; }
public String password { get; set; }
public String reenter { get; set; }
public Information(String name, String email, String phone, String zip, String state, String login, String password, String reenter)
{
this.name = name;
this.email = email;
this.phone = phone;
this.zip = zip;
this.state = state;
this.login = login;
this.password = password;
this.reenter = reenter;
}
}
Here is the code behind my Registration page:
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
Information download1 = new Information("", "", "", "", "", "", "", "");
Session["Info1"] = download1;
DropDownListState.Items.Add(download1.name);
}
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
String name = TextBoxName.Text;
String email = TextBoxEmail.Text;
String phone = TextBoxPhone.Text;
String zip = TextBoxZip.Text;
String state = DropDownListState.SelectedItem.Text;
String login = TextBoxLogIn.Text;
String password = TextBoxPassword.Text;
String reenter = TextBoxReenter.Text;
if(Session["DownloadList"] == null)
{
List<Information> downloadList = new List<Information>();
Session["DownloadList"] = downloadList;
}
Information obj1 = new Information(name, email, phone, zip, state, login, password, reenter);
List<Information> downloadList2 = (List<Information>)Session["DownloadList"];
downloadList2.Add(obj1);
Session["DownloadList"] = downloadList2;
Response.Redirect("Confirmation.aspx");
I believe these parts are working correctly because on my final page I have it printing out the user's name and email and that is working correctly.