How do I make it possible to update information in a database based on text that is input from another form?
What needs to happen (The forms used are in bold:
StudiesForm User logs in (types username and password in separate textboxes).
The information from the username textbox on the StudiesForm is saved and used as a reference in the select statement for displaying the details on the next form.
UpdateMyDetailsForm User sees their information and can update it.
Here is an attempt, however it calls the first row of data from the database and not the unique individuals.
private void UpdateMyDetailsForm_Load(object sender, EventArgs e)
{ // Select Statement to automatically Load data to the form
//VariableHandler vh = new VariableHandler();
StudiesForm sf = new StudiesForm();
sc.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from StudentRecords where ID ='" + sf.txtBoxUsername + "'", sc);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
comBoxFrm.Text = (myReader["Title"].ToString());
txtBoxFName.Text = (myReader["First_Name"].ToString());
txtBoxSName.Text = (myReader["Surname"].ToString());
txtBoxHouseNum.Text = (myReader["House/Flat_Number"].ToString());
txtBoxStreetName.Text = (myReader["Street_Name"].ToString());
txtBoxTownCity.Text = (myReader["Town/City"].ToString());
txtBoxCounty.Text = (myReader["County"].ToString());
txtBoxPCode.Text = (myReader["Postal_Code"].ToString());
txtBoxPhone.Text = (myReader["Telephone"].ToString());
txtBoxEmail.Text = (myReader["Email"].ToString());
sc.Close();
}// end of select statement
}
Second attempt I tried to save the textbox value from the StudiesForm to a seperate class, then call the variable in the SQL command. Doing this caused the form to show all the details as blank.
I believe the issue is that because the StudiesForm hides after the user has logged in, the reference to the username text box disappears.
I tried to use String.Copy(textbox) to make a unique reference however that also didn't work.
Any ideas or suggestions? - This is also not a serious project so no worries about SQLi attacks or redundant code.
I guess what I'm asking is How Do I Reference A Textbox Value On A Different Form? In C#.
Thanks
Related
How can I assign Questions columns of the database to a variable so I can then assign it to label3 and label4. Please, can anyone here help me to solve this problem because what I am trying to do is to assign a Questions for both of the answers which are stored in my database. I have selected the answers as stated in select command but how can I assign the questions for those answers to a label 3 and label 4. Help is appreciated. So, far the code is working there is no error but I want help in mentioned points please. Help is appreciated.
As it can be seen in image bellow I have column Security1 and Security2. Basically, I want to assign this to a label like Label3.Text = Security1; Label4.Text = Security2;
image
You should have if block as following.
if (reader != null && reader.HasRows)
{
Label3.Text = reader.GetString("Security1");
Label4.Text = reader.GetString("Security2");
newpass.Visible = true;
confpass.Visible = true;
Label1.Text = "New Password";
Label2.Text = "Confirm New Password";
SqlConnection cons = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
cons.Open();
SqlCommand updates = new SqlCommand("update reg set Password='" + confpass.Text + "'", cons);
SqlDataAdapter da = new SqlDataAdapter(updates);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
cons.Close();
//ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Your password has been changed')</script>");
// Response.Redirect("Default.aspx");
}
This solution is specific to your problem. I see that the code can be improved a lot but depends on your business logic and requirement.
Split your approach in two:
First, ask the user for his name. When he enters his name and clicks a button, fetch the corresponding security questions from the database and assign them to labels, e.g. Label3.Text = reader("Security1").ToString()
Second, let the user enter the answers and test them using your existing code.
I see you are using WebForms, first you need to understand how things work:
You cannot know the security questions without knowing the username, that means you have two options:
Have 2 buttons on a page
Redirect to another page
Either way you will be sending either a POST or a GET parameter containing the username.
First case notice - WebForms do not like 2 forms on one page, and you would have to separate the answers and fetch them by IDs and then add a onClick event on your second button handling the actual update of the data.
Then you will fetch it via Request.Form['username'], where username is a key defined in your form.
After fetching it you execute the reader with the given username, and then show the question in the database via reader.GetString("Security1"), and now you can fetch the inputs and pass them to onClick listener of your update button ( another way if you opted for option no 2 - onsubmit event on form ).
It is really bad to keep passwords and even security answers in plaintext format, even the security answers, google about Hashing, essentially what you do is store the hash in the database and compare user input with the hash in the database ( Same input will give same hash ( In some algorithms it won't because it uses a salt, and those algorithms already have built in compare function so you don't have to do the comparison manually ) )
So your html should look something like:
<form runat="server">
<input type="text" name="username" />
<asp:Button PostBackUrl="~/postbackurl.aspx" runat="server" Text="Submit" />
</form>
And your CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// Fetching code here
// ...
cmd.Parameters.AddWithValue("#username", Request.Form["username"]);
// ...
Label3.Text = reader.GetString("Security1");
}
}
I am saving a checkbox value using 'Yes' & 'No' and my problem is I have a button click that would allow the user to change the value.
So my logic is, if button is clicked the checkbox value that is no would change to yes.
Here is what I have to save the information originally:
public void StoredProcedure()
{
string privateItem = Private.Checked ? "Y" : "N";
connection.connection1();
if (connection.con.State == ConnectionState.Closed)
connection.con.Open();
using (SqlCommand cmd = new SqlCommand("SaveImage", connection.con))
{
cmd.Parameters.Add("#privatecheck", SqlDbType.Char).Value = privateItem;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
connection.con.Close();
}
Basically I have a stored procedure in my database that will save my information.
Now what I was thinking to update one value is to basically do the same thing but it resulted in an error for me.
Any help on how to overwrite a previously saved checkbox value would be extremely helpful!
Thanks
I am not entirely clear on what you are asking for so my answer gives two possible solutions:
If you are looking to modify whether or not the control itself is checked or not checked here is a piece of sample code from MSDN:
private void AdjustMyCheckBoxProperties()
{
// Change the ThreeState and CheckAlign properties on every other click.
if (!checkBox1.ThreeState)
{
checkBox1.ThreeState = true;
checkBox1.CheckAlign = ContentAlignment.MiddleRight;
}
else
{
checkBox1.ThreeState = false;
checkBox1.CheckAlign = ContentAlignment.MiddleLeft;
}
// Concatenate the property values together on three lines.
label1.Text = "ThreeState: " + checkBox1.ThreeState.ToString() + "\n" +
"Checked: " + checkBox1.Checked.ToString() + "\n" +
"CheckState: " + checkBox1.CheckState.ToString();
}
If instead you are looking to modify a column in a table, an UPDATE SQL statement will do that for here, MSDN has a nice walkthrough on how to use LINQ and SQL to achieve this which I would recommend reading.
However I see you are using SqlCommand so here is the example code on how to perform an update command (again) from MSDN:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
All of the above pieces should help you generate a solution.
I have a method where, when the user clicks a button, it selects data from a table and adds it to a text box. The problem is that when a user clicks 2 or more times, the display code runs once for each click and the data is displayed multiple times in the text box.
How can I clear the Text box and display the data only once?
Note: One of the Text boxes by default has a string which I use on a query that gets the data. When I clear the data, the query throws an error since it doesn't have that string I just cleared to finish the query.
This is the code method that I'm using:
private void FillFilds()
{
mycon.Open();
string queryfill= "SELECT *From master where Num=#Num";
oleDbCmd = new OleDbCommand(queryfill, mycon);
oleDbCmd.Parameters.Add("#Lot", OleDbType.VarChar, 40).Value = Numtxt.Text;
OleDbDataReader reader;
try
{
reader = oleDbCmd.ExecuteReader();
reader.Read();
Idlbl.Text += reader[0];
Datetxt.Text += reader[1];
DatePtxt.Value = Convert.ToDateTime(reader[2]);
Jobtxt.Text += reader[3];
NoBtxt.Text += reader[4];
NoPatxt.Text += reader[5];
NoMtxt.Text += reader[6];
Numtxt.Text += reader[7];
NoRtxt.Text += reader[8];
Description.Text += reader[9];
NoMatxt.Text += reader[10];
reader.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
mycon.Close();
}
I think this might clear some questions...
sorry im new at writing in forums.
You could store this default value somewhere, for example as field in the class:
private string DefaultNumber = "12345";
// ...
Then you can assign this value to the TextBox:
Number.Text = DefaultNumber; // instead of Number.Clear() or Number.Text = ""
But you should really use sql-parameters to prevent sql-injection:
string queryfill = "SELECT * From master where Number = #Number";
DataTable table = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
using (OleDbDataAdapter da = new OleDbDataAdapter(queryfill, conn))
{
da.SelectCommand.Parameters.AddWithValue("Number", Number.Text);
da.Fill(table);
}
If the text is showing up multiple times in the text box, then you must be appending it rather than setting it. Make sure that you set the .Text value of the textbox using the = sign rather than appending to whatever is there (such as with +=).
You may also want to consider hard coding your default rather than relying on it being displayed in a text box. You can check if the text box is empty or not. If it is empty, then you can use the default, if it is not empty, you can use the entered value. Use String.IsNullOrEmpty(textbox.Text) to check if the string is empty.
You should also note that your code is completely insecure and would allow someone to do anything they wanted with your database through an attack called SQL Injection. You should never allow user input to be passed directly in to a SQL statement. Instead, you should use parameterized SQL and pass the user input as a parameter. This prevents a hacker from being able to insert additional SQL commands in to the input. For example, in this case, if I put '); DROP TABLE Master; SELECT * FROM passwords(' in your textbox, it would destroy your master table.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Ask user for username and password
On click button it checks the database connected for this username and password,
When correct it stores it's ID number in a variable, by default this variable is 0.
Then I run a If-statement, if the ID is >= 0, it needs to open another form. if not it displays Error message.
MessageBox in first If case displays the correct ID (1,2,3 whatever)
Now then on Form3, just a simple textbox1.text = "hi"; gives me the error:
Object reference not set to an instance of an object c#. and it displays the textbox line.
int IDnumber = 0;
SqlCommand dataCommand = new SqlCommand(" SELECT ID FROM leden WHERE [Username]='" + username_txt.Text + "' and [Password]='" + password_txt.Text + "'", SC);
SC.Open();
IDnumber = Convert.ToInt32(dataCommand.ExecuteScalar());
SC.Close();
if (IDnumber >= 1)
{
MessageBox.Show("Logged in, welcome ID number:" + IDnumber, "test");
Form3 f3 = new Form3(IDnumber);
f3.Show();
}
else
{
MessageBox.Show("Wrong Username and/or Password");
}
}
form3:
public Form3(int _IDnumber)
{
int IDnumber = _IDnumber;
textBox1.Text = "hi";
}
Of course the textbox is a test, to show that it doesn't matter what textbox I use, it just gives me this error.
Yes, I do still use unecrypted passwords, don't know how to do that yet
You have not initialized the components on your form yet.
add
InitializeComponent();
in the beginning of your contructor.
Setting controls in a Forms constructor is not a wise idea, instead implement these things in the OnLoad event.
MSDN: http://msdn.microsoft.com/en-us/library/360kwx3z(v=vs.90).aspx, you don't want to put code in constructor, use OnLoad.
Ok, so I've got a DataGridView for some Project Management Software, I want to be able to double click a row it opens a form and fills in the fields and combo boxes with the relvant data, so that I can change what ever needs to be changed. In this case the most important thing is changing the Status. As in the Project Management Software I have bugs and tasks, that have a status and that needs to be changed at some point obviously when the Bug has been resolved or the task completed.
So I will show how the DGV is getting data for the bugs section:
public void ViewAllBugs()
{
DataClasses1DataContext dc = new DataClasses1DataContext(sConnectionString);
var Bugs =
(from data in dc.GetTable<Bug>()
from user in dc.GetTable<User>()
from projects in dc.GetTable<Project>()
from priority in dc.GetTable<Priority>()
from status in dc.GetTable<Status>()
from category in dc.GetTable<Category>()
where data.UserID == user.UserID && data.ProjectID == projects.ProjectID && data.PriorityID == priority.PriorityID && status.StatusID == data.StatusID && category.CategoryID == data.CategoryID
select new
{
Bug = data.Name,
Project = projects.Name,
Priority = priority.Priority1,
Status = status.Name,
Category = category.Category1,
Assigned_To = user.Username,
Start = data.Opened_Date,
End = data.Closed_Date,
Description = data.Description,
});
dgvBugs.DataSource = Bugs;
}
As you can see my approach is fairly simplistic. I will also show the code for creating a new Bug. The ComboBoxes have been DataBound using the GUI option as opposed to me actually hardcoding it in.
public void CreateBug()
{
string sBugName = txtName.Text;
string sDescription = txtDescription.Text;
int iProject = Convert.ToInt32(cbProject.SelectedValue);
int iPriority = Convert.ToInt32(cbPriority.SelectedValue);
int iStatus = Convert.ToInt32(cbStatus.SelectedValue);
int iCategory = Convert.ToInt32(cbCategory.SelectedValue);
int iUser = Convert.ToInt32(cbAssigned.SelectedValue);
DateTime dtOpen = dateOpened.Value;
DateTime dtClosed = dateClosed.Value;
DataClasses1DataContext dc = new DataClasses1DataContext(sConnectionString);
Table<Bug> tBug = dc.GetTable<Bug>();
Bug nBug = new Bug();
nBug.Name = sBugName;
nBug.ProjectID = iProject;
nBug.PriorityID = iPriority;
nBug.StatusID = iStatus;
nBug.CategoryID = iCategory;
nBug.UserID = iUser;
nBug.Opened_Date = dtOpen;
nBug.Closed_Date = dtClosed;
nBug.Description = sDescription;
tBug.InsertOnSubmit(nBug);
dc.SubmitChanges();
this.Close();
}
Now I know there a few bits of sloppy code in there, but i am new to C# and i personally think im not doing too badly. But if you can see anything that should be improved please feel free to mentiond that as well.
My DataClasses1DataContext is organised so that there are Associations between the UserID, PriorityID, CategoryID, UserID, ProjectID and StatusID.
So basically i want to be able to click on Bug1 (an example bug) in the DGV and that needs to open up a form (that i havnt made yet) and i need to be able to edit every piece of data in that Bug.
If you require anymore information I'll be more than happy to supply it!
Thanks,
Brendan
The DataGridView will have a CellDoubleClick event. You can use this to respond to the UI, however don't forget you need to ignore invalid row or column indexes (-1s). I believe these crop in if people click on the row/column headers.
You the event args to get the row index and then the row. From the row you can access the DataBoundItem property. This should be directly cast-able to Bug.
You can then pass this reference to your new form, bind it to the controls and make your edits. Because its a reference, it will update the data on the other form too - though you may have to refresh your grid.
You can then decide whether to update the database on the details form or the master form (I'd personally make saving part of the grid form).