Passing textbox value to a function - c#

I am having a problem with my login application. I am trying to get user type from the database based on username. When I pass the name from textbox user type will be null. Otherwise, when I declare the name manually it will work and gives the user type!!!
This is my code:
public string usertype { get { return label3.Text; } set { label3.Text = value; } }
public string username { get { return txtname.Text; } set { txtname.Text = value; } }
private void Login_Load(object sender, EventArgs e)
{
username=txtname.Text;
label3.Text=Users(username);
}
public string Users(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stock;Integrated Security=True"))
{
string sql = "SELECT usertype FROM[dbo].[LoginTable] where UserName =#UserName";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#UserName", name);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
usertype = reader["usertype"].ToString();
}
con.Close();
}
}
return usertype;
}
//Main form to access user type for security
Login login = new Login();
string type=login.usertype; //-----usertype null
Note that I am accessing user type from user_control in the main form, don't know if it differs.

It works by changing the function location to the txtname_TextChanged event. Thanks all

Related

How to add data into MSQL database by using c# programming?

Good day!
Using visual studio 2012, I have created a Student class with get and set codes, and i need to complete the StudentDAO class to create insert coding that will use to store data to database student table. this action is perform by a windows form button click event.
what i need to create a button click code and then insert into database code,
//Student.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRSJason
{
class Student
{
private string S_Student_id;
private string S_Full_name;
private DateTime S_Dob;
private string S_Address;
private int S_Contact;
private string S_Username;
private string S_Password;
public Student() //Default constructor
{
}
public Student(string Student_id, string Full_name, DateTime Dob, string Address, int Contact, string Username, string Password) //Overloadign
{
S_Student_id = Student_id;
S_Full_name = Full_name;
S_Dob = Dob;
S_Address = Address;
S_Contact = Contact;
S_Username = Username;
S_Password = Password;
}
public void setID(string Student_id)
{
S_Student_id = Student_id;
}
public string getID()
{
return S_Student_id;
}
public void setName(string Full_name)
{
S_Full_name = Full_name;
}
public string getName()
{
return S_Full_name;
}
public void setDob(DateTime Dob)
{
S_Dob = Dob;
}
public DateTime getDob()
{
return S_Dob;
}
public void setAddress(string Address)
{
S_Address = Address;
}
public string getAddress()
{
return S_Address;
}
public void setContact(int Contact)
{
S_Contact = Contact;
}
public int getContact()
{
return S_Contact;
}
public void setUsername(string Username)
{
S_Username = Username;
}
public string getUsername()
{
return S_Username;
}
public void setPassword(string Password)
{
S_Password = Password;
}
public string getPassword()
{
return S_Password;
}
}
}`
//StudentDAO class (please help me to complete this code)
`class StudentDAO
{
static string constring = "Data Source=JAZE;Initial Catalog=srsjason;Integrated Security=True";
SqlConnection m_con = new SqlConnection(constring);
}`
//button click from the form (please help me to complete this code as well)
private void submitstudent(object sender, EventArgs e)
{
}
please help me to complete this coding
First of all when you create private properties u cant access them in your forms, you have to create a method instead inside the same class then use it in your form. second you should know about the ORM - Object Relational Mapping that you are using.
Here I'll list them:
ADO.NET
LINQ to SQL
ADO.NET Entity Framework
When you picked one of those. next step would be learning about how they work and whats the syntax.
However knowing that you kinda showed a syntax of ADO.NET Here is an Example how you can insert the data in your data base using ADO.NET. If you want to add data directly from code-behind without a method. so basically on click event of your button.
private void btn_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
//Execute command by calling following method................
//1.ExecuteNonQuery()
//This is used for insert,delete,update command...........
//2.ExecuteScalar()
//This returns a single value .........(used only for select command)
//3.ExecuteReader()
//Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
Be sure that you've included your ConnectionString in your config file.

Update Collection Value with Database in UWP(MVVM)

I have custom collection which contains student_id,student_name,student_mark.And having the table with same columns in the database as well. The design form have some controls for updating the existing student.
Temporarily all the updating operations are done with that custom collection.Lets assume we have 100 students data in collection and database. Any updating operation should reflect in the collection. But what my doubt is how do i update these values with the database before i close the application??
But when i open the application the collection should have all the values which have stored in the database.
But what my doubt is how do i update these values with the database
Firstly, you need to know how to do CRUD operations on MySQL database with uwp app. For this, please reference this sample.
Secondly, according to your description, you have built up a MVVM project to bind a collection data to the view. But you didn't have a data layer for this MVVM structure. For this, you need to create a class for data layer to do GRUD operations, and establish contact with this data service from ViewModel. More details please reference this article.
The class for data layer I wrote according to your description which contains how to read, update and delete data from mysql database is as follows:
public class Student
{
public int Student_id { get; set; }
public string Student_name { get; set; }
public string Student_mark { get; set; }
}
public class DataService
{
static string connectionString;
public static String Name = "Data Service.";
private static ObservableCollection<Student> _allStudents = new ObservableCollection<Student>();
public static ObservableCollection<Student> GetStudents()
{
try
{
string server = "127.0.0.1";
string database = "sakila";
string user = "root";
string pswd = "!QAZ2wsx";
connectionString = "Server = " + server + ";database = " + database + ";uid = " + user + ";password = " + pswd + ";SslMode=None;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand getCommand = connection.CreateCommand();
getCommand.CommandText = "SELECT * FROM student";
using (MySqlDataReader reader = getCommand.ExecuteReader())
{
while (reader.Read())
{
_allStudents.Add(new Student() { Student_id = reader.GetInt32(0), Student_name = reader.GetString(1), Student_mark = reader.GetString(2) });
}
}
}
}
catch (MySqlException sqlex)
{
// Handle it :)
}
return _allStudents;
}
public static bool InsertNewStudent(Student newStudent)
{
// Insert to the collection and update DB
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "INSERT INTO student(student_id, student_name, student_mark)VALUES(#student_id, #student_name,#student_mark)";
insertCommand.Parameters.AddWithValue("#student_id", newStudent.Student_id);
insertCommand.Parameters.AddWithValue("#student_name", newStudent.Student_name);
insertCommand.Parameters.AddWithValue("#student_mark", newStudent.Student_mark);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
return false;
}
}
public static bool UpdateStudent(Student Student)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "Update student Set student_name= #student_name, student_mark=#student_mark Where student_id =#student_id";
insertCommand.Parameters.AddWithValue("#student_id", Student.Student_id);
insertCommand.Parameters.AddWithValue("#student_name", Student.Student_name);
insertCommand.Parameters.AddWithValue("#student_mark", Student.Student_mark);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
// Don't forget to handle it
return false;
}
}
public static bool Delete(Student Student)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand insertCommand = connection.CreateCommand();
insertCommand.CommandText = "Delete from sakila.student where student_id =#student_id";
insertCommand.Parameters.AddWithValue("#student_id", Student.Student_id);
insertCommand.ExecuteNonQuery();
return true;
}
}
catch (MySqlException sqlex)
{
return false;
}
}
}
For updating the database in TwoWay binding way, we can implement is by invoking the data updating method in
PropertyChanged event as follows:
void Person_OnNotifyPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
organization.Update((StudentViewModel)sender);
}
For the completed demo you can download here.

Create separate class for connection string

i am trying to create separate class for connection named Connection.cs, why am i having this error while executing the query
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed
what am i doing wrong ?
in my Dal.cs class
public void Insert(string f1,string f2)
{
string query;
Connection c = new Connection();
c.OpenCnn();
try {
query = "inset into ..."
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
catch (Exception ex){
throw ex;
}
finally {
c.CloseCnn();
}
}
and in my Connection.cs class
public class Connection
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
public void OpenCnn()
{
string cnnStr = ConfigurationManager.ConnectionStrings["myconnstrng"].ToString();
con = new SqlConnection(cnnStr);
con.Open();
}
public void CloseCnn()
{
con.Close();
}
}
Currently the con field is private and can not be accessible from outside of Connection class.
You can add a property to your connection class:
public SqlConnection Connection { get { return con; } }
Then access it via your instance:
Connection c = new Connection();
c.OpenCnn();
try
{
query = "inset into ..."
cmd = new SqlCommand(query, c.Connection);
cmd.ExecuteNonQuery();
}
Btw, I'm not sure what are you referring by con in your Insert method (probably a local variable instead of the con field, because otherwise it wouldn't even compile)
public class Connection
{
SqlConnection con;
public SqlConnection Conn { get { return con; } }
public void OpenCnn()
{
string cnnStr = ConfigurationManager.ConnectionStrings["myconnstrng"].ToString();
con = new SqlConnection(cnnStr);
con.Open();
}
public void CloseCnn()
{
con.Close();
}
}
Method Insert:
Note SqlCommand initialization and usage of public property conn.
public void Insert(string f1, string f2)
{
string query;
Connection c = new Connection();
c.OpenCnn();
try
{
query = "insert into ..."
SqlCommand cmd = new SqlCommand(query, c.Conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex){
throw ex;
}
finally {
c.CloseCnn();
}
}

Importing array values in constructor

In my main form I have the following code
[ImportingConstructor]
public MainForm([ImportMany] IEnumerable<AudioPlugin> content)
{
InitializeComponent();
listBox.DisplayMember = "Name";
foreach (var listing in content)
{
listBox.Items.Add(listing);
}
}
In my AudioPlugin class I have the following code
[Export(typeof(INAudioPlugin))]
public class RecordingPanelPlugin : AudioPlugin
{
private string _customer { get; set; }
public void ConnectionString()
{
using (var conn = new SqlCeConnection("Data Source=MyDatabase.sdf;Password=pass;Persist Security Info=True"))
{
conn.Open();
var comm = new SqlCeCommand("SELECT * FROM main", conn);
SqlCeDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
_customer = (string)(reader["CustomerName"]);
Console.WriteLine(_customer);
}
}
}
public string Name
{
get
{
ConnectionString();
return _customer;
}
}
public Control CreatePanel()
{
return new RecordingPanel();
}
}
With the code as it is, I'm only getting the last value returned from the SQL query. What am I missing?
You're assigning the value of the last read element to the variable _customer, you should use a datastructure (like a List) to keep all the elements you're getting and then pass that to the constructor.
Your code should be fixed this way:
private List<string> _customers = new List<string>();
public void ConnectionString()
{
using (var conn = new SqlCeConnection("Data Source=MyDatabase.sdf;Password=pass;Persist Security Info=True"))
{
conn.Open();
var comm = new SqlCeCommand("SELECT * FROM main", conn);
SqlCeDataReader reader = comm.ExecuteReader();
string customer;
while (reader.Read())
{
customer = (string)(reader["CustomerName"]);
Console.WriteLine(customer);
_customers.Add(customer);
}
}
}
I guess I was over-thinking this problem. I removed the Import/Export from both classes and instead decided to call the query directly in my main form so I could populate the listbox as needed. Then I'm assigning a variable to the listbox.SelectedItem and am passing that over to the AudioPlugin class. Everything is working as expected now, thanks for the suggestions to try and resolve the issue though.

How can I pass my getters and setters parameters to connection class?

I assigned the textbox inputs to getters and setters also created one connection class. How can I pass my getters and setters parameters to connection class so I can use it inside my mainform.
MemberClass
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
MainForm
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
Your method GetConnection requires three parameters. You need to pass them to the method.
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
Or you could pass the instance of UserMembers to the GetConnection method creating an overload of GetConnection like this
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
As a side note. If you need the srID member to be always in upper case then move this logic in the setter property, and you could stop to worry about the proper formatting of this member when you try to read it back
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}

Categories