Datatable does not have definition for "Getvalue" - ASP.Net - c#

I need to check & capture user login details, and store it under Session to carry forward to next page. But i am getting this error, DataTable does not have definition for "Getvalue" at Session["idname"]= dt.GetValue(0).ToString();.
The code i used,
con.Open();
SqlCommand cmd = new SqlCommand("select * from LoginDB where (EmpCode COLLATE Latin1_General_CS_AS = #EmpCode) and (Password COLLATE Latin1_General_CS_AS =#Password)", con);
cmd.Parameters.AddWithValue("#EmpCode", txtLogin.Text.Trim());
cmd.Parameters.AddWithValue("#Password", txtPwd.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["idname"]= dt.GetValue(0).ToString();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + "Login Success!" + "')</script>");
Session["identity"] = txtLogin.Text;
Response.Redirect("Mainpage.aspx", false);
}
else
{
txtLogin.Text = "";
ShowMessage("UserId / Password is Not Correct!");
}
con.Close();

The error message is clear: DataTable does not have a definition for "Getvalue".
Since DataTable has more than just one row, what you can do is to select the first row and get the value via specified column of that row:
if (dt.Rows.Count > 0)
{
var userRow = dt.Rows[0];
Session["idname"] = userRow["idName"].ToString(); //assuming you have idName column in LoginDB
//..
}
else
{
txtLogin.Text = "";
ShowMessage("UserId / Password is Not Correct!");
}
Console.WriteLine("Hello World!");
See: Get Cell Value from a DataTable in C#

Change this:
Session["idname"]= dt.GetValue(0).ToString();
To:
Session["idname"] = dt.Rows[0][0].ToString();

There is no built in function that gives you a value that is place in the datatable. Try to use object of datarow to fetch data with in row. Below is the code. Try this one.
con.Open();
SqlCommand cmd = new SqlCommand("select * from LoginDB where (EmpCode COLLATE Latin1_General_CS_AS = #EmpCode) and (Password COLLATE Latin1_General_CS_AS =#Password)", con);
cmd.Parameters.AddWithValue("#EmpCode", txtLogin.Text.Trim());
cmd.Parameters.AddWithValue("#Password", txtPwd.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
DataRow dr=dt.Rows[0];
Session["idname"]= dr[0].ToString();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + "Login Success!" + "')</script>");
Session["identity"] = txtLogin.Text;
Response.Redirect("Mainpage.aspx", false);
}
else
{
txtLogin.Text = "";
ShowMessage("UserId / Password is Not Correct!");
}
con.Close();

Related

C# Display data based on userID

Hi I'm creating a C# program where users can login and book bus seats for destinations, I have the program so users can insert/update/delete data but I want the data to just display the currently logged-in data, this is my code below.
This function is in the main dashboard class where it displays the seats table to the dataviewgrid
private void displayBookings()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
This is my database table and all I want to do once a user is logged in is display each seatID by the userID, the seatid is the primary key for this table and the userid is a foreign key linked to the userdata table.
EDIT:
private void displayBookings()
{
SqlConnection con = new SqlConnection(#"CONNECTIONSTRING");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
// the userID of the logged in user
p_userID.Value = cmd.Parameters.Add(p_userID);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Login method
private void loginButton_Click(object sender, EventArgs e)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Brandon Brock\source\repos\SE2\Booking System\Database1.mdf;Integrated Security=True"))
{
con.Open();
string str1 = "select * from userdata where username='" + log_username.Text + "' and password_1='" + log_password.Text + "'";
SqlCommand cmd = new SqlCommand(str1, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(str1, con);
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["type"] as string)
{
case "admin":
{
MessageBox.Show("You are logged in!", "Admin Portal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Admin().Show();
break;
}
case "user":
{
MessageBox.Show("You are logged in!", "Seat Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Dashboard().Show();
break;
}
default:
{
MessageBox.Show("Enter Correct Username and Password");
break;
}
}
log_username.Text = "";
log_password.Text = "";
}
else
{
MessageBox.Show("Username or Password is wrong or Account doesn't exist!", "Bus Seat Account Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
}
Assuming you have access to the logged in user data:
con.Open(); // <-- can't see where this comes from but is almost certainly an anti-pattern. Don't re-use SqlConnection instances, make new ones and Dispose() when done.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
p_userID.Value = // the userID of the logged in user
cmd.Parameters.Add(p_userID);
//cmd.ExecuteNonQuery(); <-- this is pointless, delete it
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();

Search on multiple columns - Create where clause

friends
please if you have time to solve my problem
i have many textbox in my form with one button and one datagridview
i use this code to make the search
What if i want to perform a search using values from 2 or more text boxes. what if I typed in "r" in the Name text box then also typed "NY" in the city text box. I want to see the gridview give me the results of that.
that what i try to find and i didn't find anything
the code is working if i search in one textbox only
warm regards
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (txtCIVILIDD.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where CIVILIDD = '" + txtCIVILIDD.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (txtName_Arabic.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Name_Arabic like '%" + txtName_Arabic.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (txtusername.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from Tabl1 where username = '" + txtusername.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox1.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where status = '" + comboBox1.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBox2.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where confirmation = '" + comboBox2.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (CBgender.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where gender like '%" + CBgender.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (CBNATIONALITY.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where NATIONALITY like '" + CBNATIONALITY.Text + "%'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxGovernorate.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where Governorate = '" + comboBoxGovernorate.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
else if (comboBoxCity.Text.Length > 0)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from tabl1 where City = '" + comboBoxCity.Text.Trim() + "'", con);
sda.Fill(dt);
con.Close();
}
dataGridView1.DataSource = dt;
i try to solve my problem with this code bout i find "SELECT * FROM tabl1 WHERE 1=1 ";
it return null to me
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
StringBuilder sqlcommand = "SELECT * FROM tabl1 WHERE 1=1 ";
if (!string.IsNullOrEmpty(CBgender.Text))
{
sqlcommand.Append(" and GENDER LIKE '%");
sqlcommand.Append(CBgender.Text);
sqlcommand.Append("%'");
}
// repeat for other textbox fields
dataGridView1.DataSource = dt;
}
my search form
Here are two possible approaches. The first uses #WelcomeOverflows's suggestion which is to use the RowFilter property of the DataTable. The advantage of doing so is that you only have to perform one database query and the filtering is handled client side. However, it isn't possible to protect RowFilter from SQL injection easily (but while you can still potentially subvert the filtering intention, the damage you can do on a disconnected data source is limited). Also if the dataset is enormous, it might not be desirable to pull back the entire dataset at once and keep it in memory.
// call upon startup to get all the data one time
private void GetData()
{
DataTable dataSource = new DataTable();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
connection.Open();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM tabl1", connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
// create a filter for the given field in the database and our control
private string CreateFilter(string fieldName, Control userInputControl, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
return String.Format("{0}='{1}'", fieldName, searchValue);
return String.Format("{0} LIKE '%{1}%'", fieldName, searchValue);
}
// set the filter on our data grid view
private void button1_Click(object sender, EventArgs e)
{
var filterConditions = new[] {
CreateFilter("Name_Arabic", txtName_Arabic, false),
CreateFilter("gender", CBgender, false),
CreateFilter("CIVILIDD", txtCIVILIDD, true),
CreateFilter("NATIONALITY", cbNationality, false)
// etc.
};
var dataSource = (DataTable)dataGridView1.DataSource;
if (!filterConditions.Any(a => a != null))
{
dataSource.DefaultView.RowFilter = null;
return;
}
dataSource.DefaultView.RowFilter = filterConditions
.Where(a => a != null)
.Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2));
}
Second approach is to filter directly in the database query, using SQL parameters to avoid SQL injection.
private string CreateSqlFilter(string fieldName, Control userInputControl, SqlCommand command, bool exactMatch)
{
string searchValue = null;
if (userInputControl is TextBox) searchValue = ((TextBox)userInputControl).Text;
if (userInputControl is ComboBox) searchValue = ((ComboBox)userInputControl).Text;
if (String.IsNullOrWhiteSpace(searchValue)) return null;
if (exactMatch)
{
command.Parameters.Add(new SqlParameter("#" + fieldName, searchValue));
return fieldName + " = #" + fieldName;
}
else
{
command.Parameters.Add(new SqlParameter("#" + fieldName, "%" + searchValue + "%"));
return fieldName + " LIKE #" + fieldName;
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand selectCommand = new SqlCommand();
var filterConditions = new[] {
CreateSqlFilter("Name_Arabic", txtName_Arabic, selectCommand, false),
CreateSqlFilter("gender", CBgender, selectCommand, false),
CreateSqlFilter("CIVILIDD", txtCIVILIDD, selectCommand, true),
CreateSqlFilter("NATIONALITY", cbNationality, selectCommand, false)
// etc.
};
string filterCondition = filterConditions.Any(a => a != null) ? filterConditions.Where(a => a != null).Aggregate((filter1, filter2) => String.Format("{0} AND {1}", filter1, filter2)) : (string)null;
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString))
{
selectCommand.Connection = connection;
selectCommand.CommandText = filterCondition == null ? "SELECT * FROM tabl1" : "SELECT * FROM tabl1 WHERE " + filterCondition;
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
DataTable dataSource = new DataTable();
adapter.Fill(dataSource);
dataGridView1.DataSource = dataSource;
}
}
Create StringBuilder object:
StringBuilder sqlcommand = new StringBuilder("SELECT * FROM tabl1 WHERE 1=1");
You can create a parametrized query which considers parameters having null values as neutral in search. For example:
SELECT * FROM Product WHERE
(Id = #Id OR Id IS NULL) AND
(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND
(Price = #Price OR #Price IS NULL)
This way, if you pass NULL for any of the parameters, that parameter will not be considered in search.
Also as a side note, it prevents SQL Injection, by using parameters.
Example
The following example assumes you have a table called Product, having a column named Id as INT, Name as NVARCHAR(100) and Price as INT.
Then to load data, create the following method:
public DataTable GetData(int? id, string name, int? price)
{
DataTable dt = new DataTable();
var commandText = "SELECT * FROM Products WHERE " +
"(Id = #Id OR #Id is NULL) AND " +
"(Name LIKE '%' + #Name + '%' OR #Name IS NULL) AND " +
"(Price = #Price OR #Price IS NULL)";
var connectionString = #"Data Source=.;Initial Catalog=SampleDb;Integrated Security=True";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Id", SqlDbType.Int).Value =
(object)id ?? DBNull.Value;
command.Parameters.Add("#Name", SqlDbType.NVarChar, 100).Value =
(object)name ?? DBNull.Value;
command.Parameters.Add("#Price", SqlDbType.Int).Value =
(object)price ?? DBNull.Value;
using (var datAdapter = new SqlDataAdapter(command))
datAdapter.Fill(dt);
}
return dt;
}
To get values from TextBox controls and pass to GetData, you can use the following code:
var id = int.TryParse(idTextBox.Text, out var tempId) ? tempId : default(int?);
var name = string.IsNullOrEmpty(nameTextBox.Text)?null:nameTextBox.Text;
var price = int.TryParse(priceTextBox.Text, out var priceId) ? priceId : default(int?);
Then to get data:
var data = GetData(id, name, price);

Multi user login using c# and ms access database, error is rows position?

Please help, on how to solve this one..
Here is my Login table's structure:
Username, Password, Position
Actually the code is running, and it shows the messagebox "Login Success". The problem is the form
frmHome home = new frmHome();
home.Show();
and
frmAdminHome ah = new frmAdminHome();
ah.Show();
did not show and throws an error on
if(dt.Rows[0][0].ToString()=="admin")
hmmp.. there's no row on position? seems its the errors says.
I need help on how to fix this one.. I need your guidance guys..
This code is on button click event, I am using C# and MS Access database:
try
{
string user, pass;
user = Convert.ToString(txtUsername.Text);
pass = Convert.ToString(txtPassword.Text);
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Login WHERE Username = '" +user+ "' AND Password = '" + pass + "' ";
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Success!");
this.Hide();
if (dt.Rows[0][0].ToString()=="admin")
{
frmHome home = new frmHome();
home.Show();
Visible = false;
}
else if (dt.Rows[0][0].ToString() == "staff")
{
frmAdminHome ah = new frmAdminHome();
ah.Show();
Visible = false;
}
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!");
}
else
{
MessageBox.Show("Username and Password is not correct!");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
First thing is you should not have duplicate rows having same username and password.
this should be prevented when user is created in the system. You should not allow duplicate usernames. If you handle that you won't need to check for duplicates at the time of login.
For now you can use following approach to solve your current issue.
You are getting data returned from the query into the DataReader and you read it using reader.Read() but you never populate the datatable using OleDbDataAdapter da
try
{
string user, pass;
user = txtUsername.Text; // You don't need Convert.ToString as TextBox.Text is already string.
pass = txtPassword.Text;
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
var query = "SELECT * FROM Login WHERE Username = '" +user+ "' AND Password = '" + pass + "' ";
OleDbDataAdapter da = new OleDbDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds); //Populate data set via adapter.
DataTable dt = ds.Tables[0]; //Get the first table from the dataset
int count = dt.Rows.Count;
if (count == 1)
{
MessageBox.Show("Login Success!");
this.Hide();
if (dt.Rows[0][0].ToString()=="admin")
{
frmHome home = new frmHome();
home.Show();
Visible = false;
}
else if (dt.Rows[0][0].ToString() == "staff")
{
frmAdminHome ah = new frmAdminHome();
ah.Show();
Visible = false;
}
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!");
}
else
{
MessageBox.Show("Username and Password is not correct!");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
This should help you resolve your issue.

Can help me to make Auto Generate ID?

I have form want to Auto Generate that ID from Primary Key
so that code like that
private void setidphoto()
{
DataTable dt = con.FillTable("SELECT IDPhoto FROM Produksi ORDER BY IDPhoto DESC");
if (dt.Rows.Count == 0)
{
txtIdPhoto.Text = "PH001";
}
else {
string temp = dt.Rows[0][0].ToString();
int IDplus= int.Parse(temp.Substring(2)) + 1;
string NewID = String.Format("PH{0:000}", IDPlus);
txtIdPhoto.Text = NewID;
}
}
The Error is con.FillTable cant compile or run it, can you help me
Try this
SqlConnection con = new SqlConnection("yourconnectionstringhere");
SqlCommand com = new SqlCommand("SELECT IDPhoto FROM Produksi ORDER BY IDPhoto DESC", con);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataTable dt = new DataTable();
add.SelectCommand = com;
adp.Fill(dt);

How to get cell or row value from DataTable in c#

I am trying to get the usert_id value from datatable and assign it to session variable but I am not able to get the user_id in my code. How can I do this?
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select * from students where user_name='" + loginname.Text + "' and user_password ='" + password.Text + "'", conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ShowMessage(dt.Row['.user_id.']); //<-- Problem happens here
Session["user_id"] = "bar";
Response.Redirect("dashboard.aspx");
}
else
{
Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
.user_id. is not a Row index and I doubt it's the column name... you didn't surround it with dots did you? I think it should be using Rows not Row and double quotes:
ShowMessage(dt.Rows[0]["user_id"].ToString());

Categories