For example I want to display the logged in user's information from database to another form like firstname and lastname I got no problem in admin because it only has one form or details for it. I tried passing the text in textbox username to another form and then select the passed text to display the other information of it but it won't, here's my code btw.
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
MySqlCommand comm = con.CreateCommand();
comm.CommandText = "select * from accountinfo where username = #user and pass = #password";
comm.Parameters.AddWithValue("#user", textBox1.Text);
comm.Parameters.AddWithValue("#password", textBox2.Text);
MySqlDataReader myReader;
con.Open();
comm.ExecuteNonQuery();
myReader = comm.ExecuteReader();
string accountType = string.Empty;
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(comm);
i = Convert.ToInt32(dt.Rows.Count.ToString());
while (myReader.Read())
{
i = i + 1;
accountType = myReader["accountType"].ToString();
}
if (i == 0)
{
MessageBox.Show("Wrong username or password!");
}
else if (accountType == "admin")
{
MessageBox.Show("Welcome admin");
this.Hide();
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
Form3 frm3 = new Form3();
frm3.Show();
}
else
{
MessageBox.Show("Welcome");
this.Hide();
using(var frm4 = new Form4())
{
frm4.FirstName = textBox1.Text;
frm4.ShowDialog();
}
}
con.Close();
}
and my code in second form
public partial class Form4 : Form
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CellNo { get; set; }
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
tbUser.Text = FirstName;
try
{
string MyConnection2 = "server=localhost;user id=root;database=account;persistsecurityinfo=True;PASSWORD=test123;SslMode=none";
string Query = "SELECT firstname = '" + tbFN.Text + "' from accountinfo WHERE username = '" + tbUser + "' " ;
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Logged in user information is kind of static for all your application, so you should be able to access to it from anywhere
As a solution create class user
public class User {
username, full name ...
}
Create embiend class ApplicationContext
public class ApplicationContext
{
private ApplicationContext(){
}
public User UserInfo {get;}
public static ApplicationContext Current{get;}
public static Init(User userInfo)
{
if(Current != null)
throw new Exception("Context already initialized");
Current = new ApplicationContext(){
UserInfo = userInfo
}
}
}
After login call
ApplicationContext.Init(userInfo);
Everywhere where you need user info call
ApplicationContext.Current.UserInfo
Related
I am working on a Web API in C# and am getting my data from a SQL Database. The Get method returns all rows of (student) data, however even when I put a single student number in the GET call, it still returns all rows of data instead of a single row for the specified student. In my Roles Class I have;
public class Roles
{
List<Roles> studentRoles = new List<Roles>();
public string UserName { get; set; }
public string PersonName { get; set; }
public string Profile { get; set; }
public string Level { get; set; }
public int Year { get; set; }
public string Department { get; set; }
}
public class readRoles : Roles
{
public readRoles(DataRow dataRow)
{
UserName = (string)dataRow["UserName"];
PersonName = (string)dataRow["PersonName"];
Profile = (string)dataRow["Profile"];
Level = (string)dataRow["Level"];
Year = Convert.ToInt32(dataRow["Year"]);
Department = (dataRow["Department"] == DBNull.Value) ? "No Department" : dataRow["Department"].ToString();
}
public string UserName { get; set; }
public string PersonName { get; set; }
public string Profile { get; set; }
public string Level { get; set; }
public int Year { get; set; }
public string Department { get; set; }
}
In my Controller I have this;
List<Roles> studentRoles = new List<Roles>();
private SqlDataAdapter _adapter;
public IEnumerable<Roles> Get()
{
//Create link to database
string connString;
SqlConnection con;
connString = #"XXX";
DataTable _dt = new DataTable();
con = new SqlConnection(connString);
con.Open();
var sql = "some sql here";
SqlCommand CMD = new SqlCommand();
CMD.Connection = con;
CMD.CommandText = sql;
CMD.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = CMD.ExecuteReader();
_adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(sql, con)
};
_adapter.Fill(_dt);
List<Roles> roles = new List<Roles>(_dt.Rows.Count);
if (_dt.Rows.Count > 0)
{
foreach (DataRow studentrole in _dt.Rows)
{
roles.Add(new readRoles(studentrole));
}
}
return roles;
}
The above returns all the data as it should. To return a single row of data, I have the below Method but it still returns every single row instead of the row for the specified one when I do e.g. https://localhost:XXXXX/custom-roles-api/campusCustomRoles/12345;
[HttpGet]
public IHttpActionResult Get(string userName)
{
string connString;
SqlConnection con;
connString = #"XXX";
DataTable _dt = new DataTable();
con = new SqlConnection(connString);
con.Open();
var sql = "select distinct .... where student_reference = " + userName +;
SqlCommand CMD = new SqlCommand();
CMD.Connection = con;
CMD.CommandText = sql;
CMD.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = CMD.ExecuteReader();
_adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(sql, con)
};
_adapter.Fill(_dt);
List<Roles> roles = new List<Roles>(_dt.Rows.Count);
if (_dt.Rows.Count > 0)
{
foreach (DataRow studentrole in _dt.Rows)
{
roles.Add(new readRoles(studentrole));
}
}
var singlestu = roles.FirstOrDefault(e => e.UserName == userName);
return Ok(singlestu)
;
}
In the above example, I expect only data for student 12345 to be returned, but alas, all records are retrieved. In my WebConfig file, I have a custom Route like so;
public static void Register(HttpConfiguration config)
{
// Web API routes
// This is the original Route
//config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{Controller}/{id}",
// //routeTemplate: "api/{controller}/{action}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
// Custom Route
config.MapHttpAttributeRoutes();
// Define route
System.Web.Http.Routing.IHttpRoute rolesRoute = config.Routes.CreateRoute("custom-roles-api/{controller}/{id}",
new { id = RouteParameter.Optional }, null);
// Add route
config.Routes.Add("DefaultApi", rolesRoute);
}
Not sure where I have gone wrong and would be grateful for any pointers.
Many thanks in advance.
EDIT: As requested, please see below code when I used parameters;
[HttpGet]
public IHttpActionResult Get(string userName)
{
string connString;
SqlConnection con;
connString = #"XXXX";
DataTable _dt = new DataTable();
con = new SqlConnection(connString);
con.Open();
var sql = "select distinct .... where student_reference =#UserName " +
"and department ='LAW' " +;
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserName";
param.Value = UserName;
SqlCommand CMD = new SqlCommand();
CMD.Connection = con;
CMD.CommandText = sql;
CMD.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = CMD.ExecuteReader();
_adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(sql, con)
};
_adapter.Fill(_dt);
List<Roles> roles = new List<Roles>(_dt.Rows.Count);
if (_dt.Rows.Count > 0)
{
foreach (DataRow studentrole in _dt.Rows)
{
roles.Add(new readRoles(studentrole));
}
}
var singlestu = roles.FirstOrDefault(e => e.UserName == userName);
return Ok(singlestu)
;
}
After much head-cracking, I go it to work by converting the UserName to type int in the Roles class and the source query.
I want to select an item from a combobox and it should show the item that has been selected.
When I use:
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
it will only show the number of the item
if I use
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem);
or
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedItem.ToString());
It will only print a message like "System.Data.DataRowView"
Here's the whole Code:
private void GetCategory()
{
Con.Open();
SqlCommand cmd = new SqlCommand("Select * from CategoryTBL", Con);
SqlDataReader Rdr;
Rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("CategoryName", typeof(String));
dt.Load(Rdr);
categCB.ValueMember = "CategoryName";
categCB.DataSource = dt;
Con.Close();
}
private void addbtn_Click(object sender, EventArgs e)
{
if (itemIDtxt.Text == "" || itemnametxt.Text == "" || descriptiontxt.Text == "" || manufacturertxt.Text == "" || amounttxt.Text == "" || quantitytxt.Text == "")
{
MessageBox.Show("Missing Data");
}
else
{
int tAmount = Convert.ToInt32(amounttxt.Text) * Convert.ToInt32(quantitytxt.Text);
try
{
Con.Open();
SqlCommand cmd = new SqlCommand("insert into ItemDetailTBL values(#iID, #ItemNa, #ItemCateg, #ItemDesc, #ItemMan, #ItemAmoun, #ItemQua, #ItemExDate, #ItemtAmount)", Con);
cmd.CommandType = CommandType.Text;
Int32.Parse(itemIDtxt.Text);
cmd.Parameters.AddWithValue("#iID", itemIDtxt.Text);
cmd.Parameters.AddWithValue("#ItemNa", itemnametxt.Text);
cmd.Parameters.AddWithValue("#ItemCateg", categCB.SelectedIndex);
cmd.Parameters.AddWithValue("#ItemDesc", descriptiontxt.Text.ToString());
cmd.Parameters.AddWithValue("#ItemMan", manufacturertxt.Text);
cmd.Parameters.AddWithValue("#ItemAmoun", amounttxt.Text);
cmd.Parameters.AddWithValue("#ItemQua", quantitytxt.Text);
cmd.Parameters.AddWithValue("#ItemExDate", expdatepick.Text);
cmd.Parameters.AddWithValue("#ItemtAmount", tAmount);
cmd.ExecuteNonQuery();
MessageBox.Show("New Data Has been Added to the Inventory");
Con.Close();
Showitem();
addHis();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
Here is a pattern to following. Create a class representing the category table and override ToString with what should be shown in the ComboBox.
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public override string ToString() => CategoryName;
}
Rewrite you code to read data to this pattern
public static List<Category> Categories()
{
List<Category> list = new List<Category>() ;
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand { Connection = cn,
CommandText = "SELECT CategoryID ,CategoryName FROM dbo.Categories" };
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
list.Add(new Category() { CategoryID = reader.GetInt32(0), CategoryName = reader.GetString(1) });
}
return list;
}
The method above for this example resides in a class named SqlServerOperations.
Form code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
categCB.DataSource = SqlServerOperations.Categories();
}
private void GetCurrentCategoryButton_Click(object sender, EventArgs e)
{
var current = (Category)categCB.SelectedItem;
MessageBox.Show($"{current.CategoryID,-5}{current.CategoryName}");
}
}
I am trying to write login app.
My problem is that Service gives me ArrayOfXElement instead of an object.
And I do not know how to get to this object.
Here is the code:
StartPage.xaml.cs
using (...);
namespace MyFirstProject
{
public sealed partial class StartPage : Page
{
ServiceReference1.Service1Client MyService;
public StartPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MyService = new ServiceReference1.Service1Client();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.GetSinglePassCmdResponse h = MyService.GetSinglePassCmdAsync(new ServiceReference1.Pass { nickName = tBoxNick_log.Text }).Result;
Now I thought that in h I have object and I can do smth like this:
testBlock.Text = "nickname: " + h.nickname + " password: " + h.pass;
}}}
but I got error that GetSinglePassCmdResponse does not contain a definition for 'nickname'
IService1.cs
[OperationContract]
Pass GetSinglePassCmd(Pass Pass);
[DataContract]
public partial class Pass
{
[DataMember]
public string nickName { get; set; }
[DataMember]
public string password { get; set; }
[DataMember]
public Nullable<System.DateTime> lastLogDate { get; set; }
Service1.svc
public Pass GetSinglePassCmd(Pass Pass)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Passwords WHERE nickName=#nickName", con);
cmd.Parameters.AddWithValue("#nickName", Passwords.nickName);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
con.Close();
Pass pass = new Pass();
int i = 0;
if (ds.Tables[0].Rows.Count > 0)
{
//assign dataset values to array
pass.nickName = ds.Tables[0].Rows[i]["nickName"].ToString();
pass.password = ds.Tables[0].Rows[i]["password"].ToString();
pass.lastLogDate = DateTime.Parse(ds.Tables[0].Rows[i]["lastLogDate"].ToString());
}
else pass = null;
return pass;
}
And in MyFirstProject->ServiceReferences->ServiceReference1->Reference.cs->GetSinglePassCmdResponse I got
public partial class GetSinglePassCmdResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult;
public GetSinglePassCmdResponse() {
}
public GetSinglePassCmdResponse(MyFirstProject.ServiceReference1.ArrayOfXElement GetSinglePassCmdResult) {
this.GetSinglePassCmdResult = GetSinglePassCmdResult;
}
}
Could anyone help me please... ?
PS I have also tried this:
testBlock.Text = "nickname: " + h.GetSinglePassCmdResult.nickname + " password: " + h.GetSinglePassCmdResult.pass;
I am trying to get the Form to place the login information to login to the student account using their ID and password from the DATABASE code
How do I add the studentiD and Password to the form and get it to execute?
Here is the database :
Student Class:
class Student : Person
{
private int iD;
private String password;
private String eMail;
private double gpa;
private String message;
public Student() : base()
{
this.iD = 0;
this.password = "";
this.eMail = "";
this.gpa = 0;
}
public Student(int i, String pa, String eM, int gp) : base()
{
this.iD = i;
this.password = pa;
this.eMail = eM;
this.gpa = gp;
InsertDB();
}
public Student(int iD)
{
SelectDB(iD);
}
//++++++++++++++++ DATABASE Data Elements +++++++++++++++++
public System.Data.OleDb.OleDbDataAdapter OleDbDataAdapter;
public System.Data.OleDb.OleDbCommand OleDbSelectCommand;
public System.Data.OleDb.OleDbCommand OleDbInsertCommand;
public System.Data.OleDb.OleDbCommand OleDbUpdateCommand;
public System.Data.OleDb.OleDbCommand OleDbDeleteCommand;
public System.Data.OleDb.OleDbConnection OleDbConnection;
public string cmd;
public void DBSetup()
{
// +++++++++++++++++++++++++++ DBSetup function +++++++++++++++++++++++++++
// This DBSetup() method instantiates all the DB objects needed to access a DB,
// including OleDbDataAdapter, which contains 4 other objects(OlsDbSelectCommand,
// oleDbInsertCommand, oleDbUpdateCommand, oleDbDeleteCommand.) And each
// Command object contains a Connection object and an SQL string object.
OleDbDataAdapter = new System.Data.OleDb.OleDbDataAdapter();
OleDbSelectCommand = new System.Data.OleDb.OleDbCommand();
OleDbInsertCommand = new System.Data.OleDb.OleDbCommand();
OleDbUpdateCommand = new System.Data.OleDb.OleDbCommand();
OleDbDeleteCommand = new System.Data.OleDb.OleDbCommand();
OleDbConnection = new System.Data.OleDb.OleDbConnection();
OleDbDataAdapter.DeleteCommand = OleDbDeleteCommand;
OleDbDataAdapter.InsertCommand = OleDbInsertCommand;
OleDbDataAdapter.SelectCommand = OleDbSelectCommand;
OleDbDataAdapter.UpdateCommand = OleDbUpdateCommand;
OleDbConnection.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Reg"+
"istry Path=;Jet OLEDB:Database L" +
"ocking Mode=1;Data Source=c:\\RegistrationMDB.accdb;J" +
"et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" +
"ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" +
"hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " +
"OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" +
"r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";
}
public void SelectDB(int id)
{
//++++++++++++++++++++++++++ SELECT +++++++++++++++++++++++++
DBSetup();
cmd = "Select * from Students where ID = " + iD;
OleDbDataAdapter.SelectCommand.CommandText = cmd;
OleDbDataAdapter.SelectCommand.Connection = OleDbConnection;
Console.WriteLine(cmd);
try {
OleDbConnection.Open();
System.Data.OleDb.OleDbDataReader dr;
dr = OleDbDataAdapter.SelectCommand.ExecuteReader();
dr.Read();
id=iD;
setPassword(dr.GetValue(1)+"");
setEMail(dr.GetValue(2)+"");
setGpa(Double.Parse(dr.GetValue(3)+""));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
}
public void InsertDB()
{
// +++++++++++++++++++++++++++ INSERT +++++++++++++++++++++++++++++++
DBSetup();
cmd = "INSERT into Students values(" + getID() + "," +
"'" + getPassword() + "'," +
"'" + getEMail() + "'," +
"'" + getGpa() + ")";
OleDbDataAdapter.InsertCommand.CommandText = cmd;
OleDbDataAdapter.InsertCommand.Connection = OleDbConnection;
Console.WriteLine(cmd);
try
{
OleDbConnection.Open();
int n = OleDbDataAdapter.InsertCommand.ExecuteNonQuery();
if (n==1)
Console.WriteLine("Data Inserted");
else
Console.WriteLine("ERROR: Inserting Data");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
}
public void updateDB()
{
//++++++++++++++++++++++++++ UPDATE +++++++++++++++++++++++++
cmd = "Update Students set ID = '" + getID() + "'," +
"Password = '" + getPassword() + "', " +
"Email = '" + getEMail() + "', " +
"GPA = " + getGpa();
OleDbDataAdapter.UpdateCommand.CommandText = cmd;
OleDbDataAdapter.UpdateCommand.Connection = OleDbConnection;
Console.WriteLine(cmd);
try
{
OleDbConnection.Open();
int n = OleDbDataAdapter.UpdateCommand.ExecuteNonQuery();
if (n==1)
Console.WriteLine("Data Updated");
else
Console.WriteLine("ERROR: Updating Data");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
}
public void deleteDB()
{
//++++++++++++++++++++++++++ DELETE +++++++++++++++++++++++++
cmd = "Delete from Students where ID = " + getID();
OleDbDataAdapter.DeleteCommand.CommandText = cmd;
OleDbDataAdapter.DeleteCommand.Connection = OleDbConnection;
Console.WriteLine(cmd);
try
{
OleDbConnection.Open();
int n = OleDbDataAdapter.DeleteCommand.ExecuteNonQuery();
if (n==1)
Console.WriteLine("Data Deleted");
else
Console.WriteLine("ERROR: Deleting Data");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection.Close();
}
}
public void setID(int iD)
{
this.iD = iD;
}
public void setPassword(String password)
{
this.password = password;
}
public void setEMail(String eMail)
{
this.eMail = eMail;
}
public void setGpa(double gpa)
{
this.gpa = gpa;
}
public int getID()
{
return iD;
}
public String getPassword()
{
return password;
}
public String getEMail()
{
return eMail;
}
public double getGpa()
{
return gpa;
}
public String getMessage()
{
return this.message;
}
public void displays()
{
System.Console.WriteLine("ID = "+ getID());
System.Console.WriteLine("Password = "+ getPassword());
System.Console.WriteLine("Email = " + getEMail());
System.Console.WriteLine("GPA = " + getGpa());
}
}
The Form:
namespace Students
{
public partial class StudentLogin : Form
{
public StudentLogin()
{
InitializeComponent();
}
private void Logingo_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
In your class add a boolean method to check for the credentials of the student
in your class Student.cs:
public string LogNotification{get;set;}
public bool ConfirmLogin(string id, string pw)
{
using(SqlConnection con = new SqlConnection("Your connection string here"))
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("SELECT ID, PASSWORD FROM Students WHERE ID = #ID OR PASSWORD = #PASSWORD",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = id;
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = pw;
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
ID = dr["#ID"].ToString();
Password = dr["#PASSWORD"].ToString();
}
if (ID == id && Password == pw)
{
return true;
}
else
{
LogNotification = "ID/Password is incorrect";
return false;
}
}
}
in your Form:
private void Logingo_Click(object sender, EventArgs e)
{
Student st = new Student();
If(st.ConfirmLogin(txtID.text,txtPass.text)==false)
MessageBox.Show(st.LogNotification);
else
//show next form or whatever action you prefer
}
You can try this:
private void Logingo_Click(object sender, EventArgs e)
{
int studentiD = 1;//Your ID
string Password = "1234";//Your Password
Student st = new Student(studentiD);
if (st.getID() == studentiD && st.getPassword() == Password)
{
MessageBox.Show("Login Successed.");
st.displays();//display ID,Password,Email,GPA
}
else
{
MessageBox.Show("Login Failed.");
}
}
I ideally wanted to make so that when the user is logged in and have gone to form2. That when they write new data and press save to save the data in the mysql database With their account ID in 1 column but I couldn't figure out how to do that so I am turning here for help.
Form1 relevant code:
MySqlConnection con = new MySqlConnection("server=SERVERIP;port=3306;database=DATABASE;uid=USERNAME;password=PASSWORD");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM account WHERE username='" + this.user_txt.Text + "' AND pass='" + this.password_txt.Text + "';", con);
MySqlDataReader MyReader;
con.Open();
MyReader = cmd.ExecuteReader();
int count = 0;
while (MyReader.Read())
{
count = count + 1;
}
if (count == 1)
{
this.Hide();
var form1 = new Form2();
form1.Show();
}
Form2 relevant code:
using (MySqlConnection con = new MySqlConnection("server=SERVERIP;port=3306;database=DATABASE;uid=USERNAME;password=PASSWORD"))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("insert into info(Datum,Timmar,Rast) Values(#Datum,#Timmar,#Rast)", con))
{
DateTime now = DateTime.Now;
cmd.Parameters.AddWithValue("#Datum", now);
cmd.Parameters.AddWithValue("#Timmar", textBox2.Text);
cmd.Parameters.AddWithValue("#Rast", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Sparat!");
con.Close();
}
}
So what I want todo is to add account id with that information from form2 into the database.
something like:
using (MySqlCommand cmd = new MySqlCommand("insert into info(AccountId,Datum,Timmar,Rast) Values(#AccountId,#Datum,#Timmar,#Rast)", con))
{
DateTime now = DateTime.Now;
cmd.Parameters.AddWithValue("#AccountId", ACCOUNT_ID_SOURCE);
cmd.Parameters.AddWithValue("#Datum", now);
cmd.Parameters.AddWithValue("#Timmar", textBox2.Text);
cmd.Parameters.AddWithValue("#Rast", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Sparat!");
con.Close();
}
now I have tried to use to get the user input that they typed to form2 with no luck.
var frm1 = new Form1(); //Form2
string ACCOUNT_ID_SOURCE = frm1.UserText; //Form2
public string UserText { get; private set; } //form1
UserText = this.user_txt.Text; //form1
any ideas on how to fix this?
How about this one?
Sol 1. Set a userid as a Form2's constructor parameter.
readonly string ACCOUNT_ID_SOURCE;
public Form2(string aUserID)
{
InitializeComponent();
ACCOUNT_ID_SOURCE = aUserID;
}
Sol 2. Make user information static class.
1) Class
public class UserInfo
{
public static UserInfo instance = new UserInfo();
public string LogInID { get; set; }
}
2) Form 1
UserInfo.instance.LogInID = "MyID";
3) Form 2
UserInfo.instance.LogInID; // Use this property
try this create a new class
public class UserModel
{
public int IdUser { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
then in form1 in a button click event
private void button1_Click(object sender, EventArgs e)
{
UserModel userModel = new UserModel();
using (SqlConnection conn = new SqlConnection(#"Data Source=localhost; Initial Catalog=Northwind; Integrated Security=True"))
{
//here your code to retrieve data from database
userModel.FirstName = "";
userModel.LastName = "";
userModel.IdUser = 1;
}
Form2 frm2 = new Form2(userModel);
this.Hide();
frm2.Show();
}
and in your form2
public partial class Form2 : Form
{
private UserModel UserObject { get; set; }
public Form2()
{
InitializeComponent();
}
public Form2(UserModel userModel)
{
InitializeComponent();
this.UserObject = userModel;
}
private void btnSaveData_Click(object sender, EventArgs e)
{
using (MySqlCommand cmd = new MySqlCommand("insert into info(AccountId,Datum,Timmar,Rast) Values(#AccountId,#Datum,#Timmar,#Rast)", con))
{
DateTime now = DateTime.Now;
cmd.Parameters.AddWithValue("#AccountId", UserObject.IdUser);
cmd.Parameters.AddWithValue("#Datum", now);
cmd.Parameters.AddWithValue("#Timmar", textBox2.Text);
cmd.Parameters.AddWithValue("#Rast", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Sparat!");
con.Close();
}
}
}