I want to update this form's Login and Logout Time:
My code is :
protected void btnUpdate_Click(object sender, EventArgs e)
{
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
long DayLogId = Convert.ToInt64(Request.QueryString["ID"]);
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =#"Data Source=DELL\SQLSERVER1;Initial Catalog=LoginSystem;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [DayLog] SET [LoginTime]=#LoginTime,[LogOutTime]=#LogOutTime WHERE [DayLogId]=#DayLogId");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#LoginTime", LoginTime);
dataCommand.Parameters.AddWithValue("#LogOutTime", LogOutTime);
dataCommand.Parameters.AddWithValue("#DayLogId", DayLogId);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
At the first two lines of method ,
string LoginTime = txtIn.Text;
string LogOutTime = txtOut.Text;
when I debug , it does not show the value that I reinserted. This code works if I mannually write
string LoginTime = "11:44:11";
string LogOutTime = "12:44:11";
NOTE:
The value of forms in text box is coming from another page GridView.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
GridViewRow grRow = ((Control)e.CommandSource).NamingContainer as GridViewRow;
Label DayLogId = grRow.FindControl("lblDayLogId") as Label;
if (Convert.ToInt16(DayLogId.Text) > 0)
{
Response.Redirect("~/Employee/OutLog_Day.aspx?ID=" + DayLogId.Text, false);
}
}
}
You should make sure that the text box gets populated before the click event runs. As Steve suggested, usually you get this when you initialize the data on every postback which is unnecessary if the data is not changed.
Related
In my winform, there's a datatable with 2 column, 1st one is studentname & 2nd column is StudentAverage.
First txtbx is autosuggest(studentname).
How to make the second txtbx automaticaly fill according to 1st txtbx (2nd txtbx fill with the corresponding record of second column (studentsavrage)?
this is for the 1st txtbx; shows StudentNames
private void txtbxName_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string StrCmd = "SELECT * FROM School";
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\School_Database.accdb";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
OleDbCommand Cmd = new OleDbCommand(StrCmd, MyConn); ;
OleDbDataReader ObjReader = Cmd.ExecuteReader();
if (ObjReader != null)
{
while (ObjReader.Read())
namesCollection.Add(ObjReader["StudentName"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
ObjReader.Close();
MyConn.Close();
txtbxName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtbxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtbxName.AutoCompleteCustomSource = namesCollection;
}
I assume you are developing with WinForms.
First out: since a where clause is missing from your query you are not filtering while user inputs text. You should move AutoCompleteStrinCollection fetching in another place if you don't want that.
Your problem: the simplier way here is to manually update the second textbox in your txtbxName_TextChanged method.
private void txtbxName_TextChanged(object sender, EventArgs e)
{
string StrCmd = String.Format( "SELECT AGE FROM School WHERE name '{0', txtbox1.Text");
//perform query as you already do and read result
textbox2.Text = cmd.ExecuteScalar()
}
P.S: in real world things are not done the way you are doing under many many aspects
I have an asp.net page with behind C# code.
I add a page Item in main page. then I used some web user control.
In one of them, when I use this Item in page_load. it has correct value, but when I use it in another private function in same web control, it has null value!
then I prefered to use a public string and set the value of that Item in it. but not working too.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
...
second function (method) is:
private void Change_Status(string newStatus)
{
//ReqID0=Page.Items["ReqID"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Page.Item refreshes with each post back and you have to add it every time your page refreshes ,,and as per your code here in Page_Load event
if (!this.IsPostBack)
{
ReqID0 = Page.Items["ReqID"].ToString();
ReqIDLbl.Text = ReqID0;
--Assigning of value is getting bypassed when your page does a post back and you get Null value in your Change_Status method. Try using Viewstate Instead.
Use the Items property to store objects with the same lifetime as the page request. MSDN
Update: try using ViewState.
if (!this.IsPostBack)
{
ViewState["ReqID"]= ReqIDLbl.Text;
//ReqID0 = Page.Items["ReqID"].ToString();
//ReqIDLbl.Text = ReqID0;
private void Change_Status(string newStatus)
{
//ReqID0=ViewState["ReqID"].ToString();
The global variables are created / intialized between postback in asp.net and they do not retain the values between postback as http is stateless protocol, you need to use ViewState for that.
public string ReqID0;
string Status0 { get; set; }
string Status = "";
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection sqlc4;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReqIDLbl.Text = ReqID0;
ReqID0 = ViewState["ReqID0"].ToString();//ViewState
/*In case if the above code doesn't work use
ReqIDLbl.Text = ViewState["ReqID0"].ToString();*/
------
}
//Second Function
private void Change_Status(string newStatus)
{
ReqID0=ViewState["ReqID0"].ToString();
sqlc4 = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Request SET Status=#newStatus WHERE ID=#ReqID";
cmd.Parameters.AddWithValue("#newStatus", newStatus);
cmd.Parameters.AddWithValue("#ReqID", ReqID0);
cmd.Connection = sqlc4;
sqlc4.Open();
cmd.ExecuteNonQuery();
sqlc4.Close();
}
Hope This might give you the answer
edit: Solved
I have a label that gets populated with a value from a database. If the user enters this value into a textbox below, I want to change the background. The label displays the value fine on screen, but when I try to match the values in the textbox's textchanged event, it shows as null.
public void button1_Click(object sender, RoutedEventArgs e)
{
txtAnswer.Clear();
txtAnswer.Background = Brushes.White;
int number = r.Next(3) + 1;
string queryEnglish = "SELECT englishVerb FROM verbTable WHERE (verbID = " + number + ")";
string queryFrench = "SELECT frenchVerb FROM verbTable WHERE (verbID = " + number + ")";
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\verbs.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand command = new SqlCommand(queryEnglish, con))
{
this.lblEnglishVerb.Content = (string)command.ExecuteScalar();
}
using (SqlCommand command = new SqlCommand(queryFrench, con))
{
this.lblFrenchVerb.Content = (string)command.ExecuteScalar();
}
}
}
public void txtAnswer_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtAnswer.Text == lblFrenchVerb.Content.ToString())
txtAnswer.Background = Brushes.LightGreen;
if (txtAnswer.Text == "test")
txtAnswer.Background = Brushes.AliceBlue;
}
Textchanged will probably get triggered the moment 'nothing' is placed into the Content. So on the first txtAnswer_TextChanged you might get nothing.
i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command
ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
I'm currently trying to find a textbox control in InsertItemTemplate to test against values already in one of my database tables but I can't seem to get the FindControl to work. Below is the code I'm currently looking at:
protected void InsertButton_Click(object sender, EventArgs e)
{
TextBox linkinsTextBox = Page.FindControl("linkinsTextBox") as TextBox;
String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
bool exists = false;
//The number of entries in links is counted
String linkCountQuery = " SELECT COUNT(link) from[links] where link = " + linkinsTextBox.Text + "";
SqlCommand linkCountQueryCommand = new SqlCommand(linkCountQuery, myConnection);
Int32 linkCountQueryCommandValue = (Int32)linkCountQueryCommand.ExecuteScalar();
myConnection.Close();
if (linkCountQueryCommandValue >= 1)
{
exists = true;
URLexists.Text = "URL already exists. Please enter a different URL.";
}
}