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());
Related
I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.
This method shows all data from my CarAdd table:
void Bindata()
{
SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.ItemsSource = dt.DefaultView;
}
But, now I need to show the username from the UserAuth table in the dataGridView1 section.
I have tried this code:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
// dataGridView1.ItemsSource = dt.DefaultView;
}
Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:
private void save_Click(object sender, RoutedEventArgs e)
{
if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
{
try
{
con.Open();
string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";
SqlCommand cmd = new SqlCommand(newcon, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully inserted");
Bindata();
// TimeShow();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Invalid credentials");
}
}
Note: I have created a WPF Windows application for this project
Thank you!
Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.
SELECT UserName
FROM UserAuth
So for the Bindatausername() method, the SqlCommand should be changed to the following:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);
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();
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);
I have a login window in which the user should enter the user ID and password if the textBoxes are empty or the entered values are incorrect then the program should catch this showing an error message
I have written this code but it works only when the two textBoxes are empty whereas in the case of one of the textBoxes is empty or value entered for ID or password is incorrect the program stands with no reaction .. what is wrong with my codes .. regards
private void loginbtn_Click(object sender, EventArgs e)
{
try {
id = Convert.ToInt32(empIdtxt.Text);
cn.Open();
SqlCommand cmd = new SqlCommand("select empId,empPass from emp where empId='" + empIdtxt.Text + "' and empPass='" + passtxt.Text + "'", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlCommand cmd2 = new SqlCommand("insert into empLogin (empId,empPerm) select empId,empPerm from emp where empId='" + empIdtxt.Text + "'", cn);
cmd2.ExecuteNonQuery();
MainFrm mainfrm = new MainFrm(id);
mainfrm.Show();
this.Hide();
}
}
catch
{
MessageBox.Show("User ID or password invalid or incorrect","Invalid ID or password",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
finally
{
cn.Close();
}
You are missing the else block of if (dt.Rows.Count > 0). Also it is a good practice to use bind variables instead of embedding values into the query.
I have one column in SQL table. which name is Intime. Its data type is nvarchar. It stores both date and time. But I want date and time separately.
I have tried this query:
select AttendanceDate,
SUBSTRING(convert(varchar,intime,113),1,11)[Intime],
SUBSTRING(convert(varchar,intime,113),13,19)[InTime],
InDeviceId,
OutTime,
OutTime,
OutDeviceId,
dbo.MinutesToDuration(duration) as Duration,
Status
from dbo.AttendanceLogs
where EmployeeId=2938
order by AttendanceDate desc
but if I pass same SQL command in grid view its not working.
public void Bind()
{
SqlCommand cmd = new SqlCommand("select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTime],SUBSTRING(convert(varchar,InTime,113),13,19) as [Intime],InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem + " and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
Where possibly could be the problem?
replace your code with this
public void Bind()
{
SqlCommand cmd = new SqlCommand(#"select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTimeD],SUBSTRING(convert(varchar,InTime,113),13,19) as [IntimeT],
InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs
where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem.Value +
" and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
this line not filter any year it return object of drop down list
year(AttendanceDate)=" + ddlYear.SelectedItem + "