Check at run time if primary key exists - asp.net

I am working in asp.net. I have a textbox named formidtxt and another textbox is colortxt. Now what I want is that when a user enters an Form ID in formidtxt then at the same time it should start checking whether there already exists a form id with same ID that has been entered and if Form ID already exists in database then the color of colortxt textbox should change to red else it should be green.
I have an idea that it can be done by using events in text boxes but can't understand the working. My database is in SQL Server 2008.

Try this C# code;
private void Page_Load(object sender, EventArgs e)
{
// formidtxt is the name of the textbox
this.formidtxt.TextChanged += FormIDTextBox_TextChanged;
formidtxt.AutoPostBack = true;
}
Note that this method was written inside the Page_Load method.
TextChanged is an event and it occurs when the text is modified in a TextBox.
In this case, when the formidtxt (textbox) text changes, it will call the FormIDTextBox_TextChanged method.
private void FormIDTextBox_TextChanged(object sender, EventArgs e)
{
int x = 0;
// convert textbox text (string) to int
Int32.TryParse(formidtxt.Text, out x);
// call IsIDAvailableDAO method
// x is the converted int value
if (IsIDAvailableDAO(x))
{
colortxt.BackColor = System.Drawing.Color.Red;
}
else
{
colortxt.BackColor = System.Drawing.Color.Green;
}
}
This method will get the text from the textbox (formidtxt) and send it to the IsIDAvailableDAO method as a parameter.
Using the IsIDAvailableDAO method, we can check whether the ID is available in the database or not. If it is available, then the method will return a TRUE boolean value. If not, it will return a False boolean value.
According to that boolean value, you can change the color of the colortxt textbox as you want or do something else.
private Boolean IsIDAvailableDAO(int id)
{
Boolean output;
using (SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Testing;Integrated Security=True"))
{
string query = #"SELECT CASE WHEN COUNT(ID) >= 1 THEN CAST( 1 as BIT ) ELSE CAST( 0 as BIT )
END As IsAvailable
FROM TableName
WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(query, myConnection);
cmd.Parameters.AddWithValue("#ID", id);
myConnection.Open();
output = (Boolean)cmd.ExecuteScalar();
myConnection.Close();
}
return output;
}
In this method (IsIDAvailableDAO), Please change the query (TableName, ID, etc.) and connectionstring as appropriate.
You also has to add this namespace: using System.Data.SqlClient;
https://www.connectionstrings.com/sql-server-2008/
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces

Related

Filtering Web Forms GridView based on DatePicker not returning data

I have a web form with a gridview and two datepickers and a submit to submit the new query with the datetime constraints. to be the start and end dates to filter the data. The data loads fine without the data and when the submit button with the chosen dates is clicked, nothing happens. I wonder if the filtered data isn't being bound properly(I'm new to web forms and gridview.)
Here is the codebehind for the page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindDataToGridView();
}
protected void dashboard_RowEditing(object sender, GridViewEditEventArgs e)
{
gridErrors.Text = string.Empty;
dashboard.EditIndex = e.NewEditIndex;
BindDataToGridView();
}
protected void dashboard_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
dashboard.EditIndex = -1;
BindDataToGridView();
}
protected void dashboard_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dashboard.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
protected void dashboard_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
gridErrors.Text = string.Empty;
GridViewRow tabRow = (GridViewRow)dashboard.Rows[e.RowIndex];
HiddenField hdnTabId = (HiddenField)tabRow.FindControl("hdnTabId");
TextBox TxtName = (TextBox)tabRow.Cells[1].Controls[0];
}
protected void button1_Click(object sender, EventArgs e)
{
var start = startDate.Text;
var startTime = DateTime.Parse(start);
var sqlStart = startTime.ToString("yyyy-MM-dd");
var end = endDate.Text;
var endTime = DateTime.Parse(end);
var sqlEnd = endTime.ToString("yyyy-MM-dd");
string sqlQuery = "SELECT TOP(100) TabID, TabName, Title, CreatedOnDate, TabPath From TableName " +
"where CreatedOnDate >= " + sqlStart + " and CreatedOnDate <= " + sqlEnd + " Order By TabName";
BindDataToGridView(sqlQuery);
}
public void BindDataToGridView(string sqlQuery =
"SELECT TOP(100) TabID, TabName, Title, CreatedOnDate, TabPath From TableName Order By TabName")
{
var connectionFromConfig = WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection db = new SqlConnection(connectionFromConfig))
{
try
{
db.Open();
SqlCommand command = new SqlCommand(sqlQuery, db);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count > 0)
{
dashboard.DataSource = dataSet;
dashboard.DataBind();
}
}
catch (SqlException ex)
{
gridErrors.Text = ex.Message;
}
finally
{
db.Close();
db.Dispose();
}
}
}
OnPageIndexChanging Method
protected void dashboard_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dashboard.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
ok, you found the issue (missing quotes). But, at the end of the day?
Yes, everyone will come pile in and note how "when" taking user input, you don't want to concatenate into the sql (too high risk for sql injection).
However, JUST telling you not to concatenate parameters don't help UNLESS we ALSO give you a nice design approach. Looking at your code, you did a GREAT idea to have one grid view load routine. And you ALSO want with great ease to pass sql to that one routine. However, that great idea + goal conflicts with using strong typed parameters.
So, lets kill two birds with one stone here.
and find that using parameters is often LESS code over all then a long messy sql string, which is prone to errors (quite much why you had to post here).
And for numbers - no quotes, for strings - yes, and for dates, again yes. So that's an extra developer workload. And that long messy string is HARD to write, debug, and manage.
So, I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindDataToGridView();
}
void BindDataToGridView(SqlCommand cmdSQL = null)
{
// default sql
if (cmdSQL is null)
{
cmdSQL = new
SqlCommand("SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName Order By TabName");
}
using (cmdSQL)
{
cmdSQL.Connection = new SqlConnection(conString);
cmdSQL.Connection.Open();
DataTable rst = new DataTable();
rst.Load(cmdSQL.ExecuteReader());
dashboard.DataSource = rst;
dashboard.DataBind();
}
}
note several things:
We did NOT have to create a separate connection object - sqlcommand has one!!
(and since we did not create a separate connection object, then disposing of the sql command takes care of that with our using block!!!
We did not need a separate datatable/dataset, and we did NOT need a data adaptor, and we did NOT need a reader either!! (sql command object has a reader too!!!).
So, now we can call our load grid without a parameter.
But, for the case WHEN we want to pass sql with parameters? Then we can do this:
{
string sqlQuery
= "SELECT TabID, TabName, Title, CreatedOnDate, TabPath From TableName " +
"WHERE CreatedOnDate >= #Start AND CreatedOnDate <= #End ORDER By TabName";
SqlCommand cmdSQL = new SqlCommand(sqlQuery);
cmdSQL.Parameters.Add("#Start", SqlDbType.Date).Value = startDate.Text;
cmdSQL.Parameters.Add("#End", SqlDbType.Date).Value = endDate.Text;
BindDataToGridView(cmdSQL);
}
So, in fact, we can have parameters, we can have less code. We can have easy to read SQL, and we can pass the cmd SQL to that one routine.
So it NOT ONLY the suggesting to not concatenate strings, but with the right approach, we don't have to, we get strong data type conversion, and less code, and even less chances of errors in that code.
Also, check if the sql server column is a date, or datetime. If it is datetime, then specify that data type in the query parameter.
Also, you can droop the TOP clause - it only required when creating a SQL view which in theory does not support a sorted output. But for raw sql, then you can drop the TOP clause.
I needed to add single quotes before and after the sqlStart and sqlEnd variables for Sql Server to use the values with comparison operators.

Submit button to update database, won't work if there is postback stated in page_load

I have a web form page that I am going to query the data from database via selecting different values from dropdown list, after I selected proper value, in the description I want to update the database record while I click the submit button, for example, customer name, and status, there will be only one record coming back and the description will show(I can do it in isPostback and query the database, using SQL DataReader and then call related index element to get it) but when I typed something in the description and click submit, it won't update in the database, but if I don't use if(isPostback) it is working.
P.S. if there is no if(ispostback) case block there,dataUpdate.Update() works well.
So my question is;
protected void btnSubmit_Click(object sender, EventArgs e)
{
dataUpdate.Update();
}
The page_load code:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
SqlConnection conn1 = new SqlConnection(cxInfo.ConnectionString);
string userInfoQuery1 = "select * from users where id=#id";
SqlCommand userInfo1 = new SqlCommand(userInfoQuery1, conn1);
userInfo1.Parameters.AddWithValue("#id", dropdlCx.SelectedValue);
conn1.Open();
SqlDataReader reader1 = userInfo1.ExecuteReader();
reader1.Read();
if (reader1.HasRows )
{
lblCxId.Text = "" + reader1[0];
SqlConnection conn = new SqlConnection(dataUpdate.ConnectionString);
string userInfoQuery = "select cx_first_name+',' + cx_last_name as 'name',cx_id ,incident_id,description,contact_method from incident where cx_id=#id and status=#status";
SqlCommand userInfo = new SqlCommand(userInfoQuery, conn);
userInfo.Parameters.AddWithValue("#id", lblCxId.Text);
userInfo.Parameters.AddWithValue("#status", dropStatus.SelectedValue);
conn.Open();
SqlDataReader reader = userInfo.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
lblCxId.Text = "" + reader1[0];
txtDesc.Text = (string)reader[3];
radioContact.SelectedValue = (string)reader[4];
desc= (string)reader[3];
}
conn.Close();
}
conn1.Close();
}
if (IsPostBack)
{
lblCxId.Text = dropdlCx.SelectedValue;
/*I want to have txtDesc.txt= database query here, but as long as I add the code here, then the update won't work*/
}
}
So I think there only thing I got stuck is how to let the system know that what I submit is not the thing that he is going to refresh, please accept my value instead of the refresh?

Accessing User's specific data ASPX / .MDF table

I am using Visual studio and have the following page_load function on my Default.aspx web form:
if (IsPostBack == false)
{
//Display all records on the form load
DisplayCars("");
I have a user, where I can get their username (which I have used to add as the "Creator" of the specific data record). I want to use this username to only display cars where the username = ACar.Creator
How would I go about doing this? I have everything setup in order to do this.
I need something like the following:
if (User.Identity.Name == ACar.Creator) {
show this record
}
But I do not know the syntax for this within aspx/sql
Thanks
You should actually do this in the database by passing username
public DataTable GetUserRecord(string userName)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("connection string to database");
using(conn)
{
string sql = "SELECT car.CarName, car.Model FROM car WHERE car.Creator = #UserName";
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.AddWithValue("#UserName", userName);
dt.Load(comm.ExecuteReader());
}
return dt;
}
From your page
protected void Page_Load(object sender, Eventargs e)
{
DataTable dt = GetUserRecord(User.Identity.Name);
if(dt.Rows.Count > 0)
{
string firstRowCarName = dt.Rows[0]["CarName"];
//etc
}
}

The ControlToValidate property of 'NameValid' cannot be blank

i m writing a web application and i have a problem in one on my pages!
i design a admin page and i want to log in before user enter in this page!
there are three RequiredFieldValidator and a button(AddButton) in my page and i want to check the fields when user click the button but when the page is loaded the validation is checked and visual studio throw a exception:
"The ControlToValidate property of 'NameValid' cannot be blank" NameValid is one of my Validation controls in page!
and another question: what is the advantage of (using) block when you work with databases and files?
my class is here:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//a page for log in
Response.Redirect("~/LogIn.aspx");
}
}
protected void Page_Error(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<h2>Exception</h2><br />");
Response.Write(Server.GetLastError().Message);
Server.ClearError();
}
protected void AddButton_Click(object sender, EventArgs e)
{
const string ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\rasoul\sourcecode\ASP-PROJECTS\UniversityDataBase\DataBase\PersonDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection con=new SqlConnection(ConnectionString))
{
string ID = IDField.Text.Trim();
string Name = NameField.Text.Trim();
string LastName = LastNameField.Text.Trim();
DataSet data = new DataSet();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("insert into StudentTable values('{0}','{1}','{2}')", ID, Name, LastName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
what should i do?
In required field validators you MUST specify the ControlToValidate - the control you which to validate that it is required.
MSDN Description - Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. (Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx)
The advantage of the using block is it ensures the correct use of IDisposable objects.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
is equivalent to
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Source: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
you have to check controltovalidate. you have to assign controller.

Question about inserting Users/Members into a database table!

My registration form has got a CreateUserWizard. I used its event that is fired after the user is created.
Then I obtain the users identity and key. In the last line, I send the unique key to a function inside a class that should insert the key into the Users table (the field is a primary key and is unique).
public partial class Registration : System.Web.UI.Page
{
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);
int i =(int) CurrentUser.ProviderUserKey;
RegisterAdo.InsertUsers(i);
}
}
Below, I execute the query with the value that I passed and insert the user into a database
class RegisterAdo
{
public static void InsertUsers(int UsersIDentity)
{
string myConnectionString = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
SqlConnection sqlConnect = new SqlConnection(myConnectionString);
SqlCommand sqlCommand = new SqlCommand(RegisterAdo.insertCommand(UsersIDentity), sqlConnect);
try
{
sqlConnect.Open();
sqlCommand.ExecuteNonQuery();
}
catch (Exception x)
{
}
finally
{
sqlConnect.Close();
}
}
public static String insertCommand(int UsersIdentityToinsert)
{
string insertCommand="INSERT INTO Users(";
insertCommand += "UserID)";
insertCommand += "VALUES('";
insertCommand += UsersIdentityToinsert+"')";
return insertCommand;
}
My question is whether it is the best way to insert UserID into a table, and whether I do it right at all. I need the UserID to be unique, and the whole command executed with no fail...(just after the user was created and the whole UserCreateUser finished validating the user!!!
I would change two things mainly:
don't concatenate together your SQL statement - this opens doors to SQL injection attacks. Use parametrized queries instead - they are both safer, and they perform better (since only a single copy of the query's execution plan needs to be created and cached and will be reused over and over again)
put your SqlConnection and SqlCommand objects into using blocks so that they'll be automatically freed / disposed when the using blocks ends (and you can save yourself the finally block of the try...catch construct, too!).
So my code would look like this
public static void InsertUsers(int UsersIDentity)
{
string myConnectionString = WebConfigurationManager.ConnectionStrings["YourGuruDB"].ConnectionString;
string insertStmt =
"INSERT INTO dbo.Users(UserID) VALUES(#UserID)";
using(SqlConnection _con = new SqlConnection(myConnectionString))
using(SqlCommand _cmd = new SqlCommand(insertStmt, sqlConnect))
{
_cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = UsersIDentity;
try
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
catch (Exception x)
{
// do something if error occurs
}
}

Resources