Trying to UPDATE the SELECTED row from the database in c# - c#

I'm trying to give my client a way to SELECT a specific row by typing the id which is the auto incremented primary key of the table.
But there's an issue Showing the Selected row to the client using Text Boxes and letting the client UPDATE the row's cells by editing the Text Boxes and pressing another button.
I'd be glad if you guide be how to do this since I haven't got any help from the search results.
Here's the uncompleted code:
private void LookUpBtn_Click(object sender, RoutedEventArgs e)
{
if (UserIDUpdateTB.Text == "")
{
MessageBox.Show("Customer ID is needed.", "Error");
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-8QAH8VK\SQLDB; Initial Catalog=Restaurant_DB; Integrated Security=True;");
con.Open();
SqlCommand lookforcustomer = new SqlCommand("LookForCustomer", con);
lookforcustomer.CommandType = CommandType.StoredProcedure;
lookforcustomer.Parameters.AddWithValue("userid", UserIDUpdateTB.Text);
//lookforcustomer.ExecuteNonQuery();
SqlDataReader reader = lookforcustomer.ExecuteReader();
reader.Read();
object test = reader.GetValue(1);
MessageBox.Show(test.ToString(), "Error");
var id = (int?)lookforcustomer.ExecuteScalar();
con.Close();
}
}
Here's the user interface:
The client enters the customer ID , presses the look up button and five cells of the row which belongs to the entered ID, appear in five other Text Boxes separately. the client makes whatever changes he/she wants by Changing the Text Boxes' text and pressing the "Update Info" button.
I'd be thankful if you help.

This is not a sql/database question, its a question regarding your UI. I'm assuming its WPF, although WinForms properties were pretty similar too.
Each button should have a separate _Click event right? So in the UpdateInfo_click, you can either send a full UPDATE statement to SQL, or detect changes between a model in memory and what is in each TextBox.Text and only update those which change (or best yet in the where clause say WHERE Name = {old value})
Also on each of your buttons you can set a Command= property, which is needed if this were part of a repeater or similar, and you can have the same handler inspect what command it was called with to determine the action needing to be taken

So I think if I understand right, basically what you want to do is pull a customers information when the lookup button is clicked, and update the customers information when the submit button is clicked. Possibly you want to also be able to add new records?
Some of the data readers are a little different, I've used Odbc and Npgsql. But I will try and show the basics of what you want below.
I like to have a separate class that deals with the Database connection, I use a method similar to this to run queries.
private SqlDataReader Query(string query)
{
SqlCommand command = null;
SqlDataReader result_reader = null;
try
{
//conn.Open();
command = new SqlCommand(query_to_perform, database_connection); //database_connection is the same as the as your "con" variable
result_reader = command.ExecuteReader();
this.successful_query = true;
this.error_message = "";
//conn.Close();
}
catch (SqlException ex)
{
this.successful_query = false;
this.error_message = ex.Message;
//destroy the connection on a failure
database_connection = new SqlConnection();
throw;
}
return result_reader;
}
Next we basically need to fill the text boxes from a select statement where the customer id is equal to the customer id on the table
private void LookUpBtn_Click(object sender, RoutedEventArgs e)
{
SqlDataReader reader = ConnectionClass.Query("SELECT * WHERE customer_id = '" + customerIdTextbox.Text + "';")
if (reader.Read())
{
//reader[0] probably is CustomerId
NameTextbox.Text = reader[1].ToString();
LastNameTextbox.Text = reader[2].ToString();
PhoneNumberTextbox.Text = reader[3].ToString();
CellphoneNumberTextbox.Text = reader[4].ToString();
AddressTextbox.Text = reader[5].ToString();
}
}
Update the customer, I'd suggest disabling the CustomerId box after they pull up an account, or they might change the number and update a different customer with all the information pulled from the first customer,
private void SubmitBtn_Click(object sender, RoutedEventArgs e)
{
if (//!exists)
{
CreateNewCustomer();
}
else
{
ConnectionClass.Query("UPDATE table SET name = '" + NameTextbox.Text + "', lastname = '" + LastNameTextbox.Text + "', phonenumber = '" + PhoneNumberTextbox.Text + "', cellphonenumber = '" + CellphoneNumberTextbox.Text + "', address = '" + AddressTextbox.Text + "' WHERE CustomerID = '" + customerIdTextbox.Text + '";");
}
}
I believe this should give you the very basics of what you are trying to do, you can still do the queries the way you were if you don't want to create a separate class to deal with the db connection. You might also want to look in to preventing SQL Injections, you will need to deal with things like apostrophes in the text, and creating a new customer will just use an insert query.

Related

i am getting an error at oledbdatareader saying no given value for one or more required parameters in ASP.NET

I have a webpage called blogwebsite and in that I have a textbox and search button. I am passing the value of textbox on button click to another webform called blogseacrh through session. I also have a database bound through these webforms. In this blogsearch webpage I have taken the session variable in a textbox. Using this textbox value I am writing a oledbcommand select query. I am fetching data from the database using this textbox value and want to display it on the blogsearch webpage. For this to happen I am using oledbdatareader to read the data and then write the fetched data in the textbox. But when I am running the webpage when I click on search button it gives me the error at the oledbdatareader line saying that no given value given for one or more required parameters.
I really can't understand what I am doing wrong. Can someone please give me a solution?
This is the button click event which is working perfectly
protected void btn_srch_Click(object sender, EventArgs e)
{
Session["name"] = txt_bnm.Text;
Response.Redirect("blogseacrh.aspx");
}
This is the code that needs to be executed on another webpage on button click event
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
con.Open();
txt2_bnm.Text = Session["name"].ToString();
cmd = new OleDbCommand("select user from tbl_blogs where book_name='" + txt2_bnm.text + "',con); `
OleDbDataReader d = cmd.ExecuteReader();
while (d.Read())
{
user = d["user"].ToString();
Response.Write(user);
}
cmd = new OleDbCommand("select blogs from tbl_blogs where book_name='" + txt2_bnm.Text + "' ", con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
blogs = dr["blogs"].ToString();
Response.Redirect(blogs);
}
con.Close();
}
I have also checked all the field names and table name and they are all correct as well.
Can someone please solve this error. i have an assignment to complete please.

Joining two ID's together to get another Column Result

I am using Windows Form and C# and an SQlite Database. I have a Combo Box with the Player's Name and below i have a textbox which i need to fill with the Overall Rating
I have two tables named Player and Player_Attributes. Now i need to join the Player_Api_ID so that i can get the Overall Rating Result from the Player_Attributes table according to the Player's Name found in the Player Table. Can someone show me how the statement can be done? Thanks
Player Table1
Player_Attributes Table
UI
Dropdown Code
private void playersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string filename = #"C:\Users\nicho\Documents\nicholas2ndyearproject\database.sqlite";
var conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;");
{
using (SQLiteCommand cmd = new SQLiteCommand("SELECT player_name, Player_Attributes.sprint_speed FROM Player JOIN Player_Attributes ON Player.player_api_id = Player_Attributes.player_api_id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.AddWithValue("#player_api_id", playersListBox.SelectedValue);
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txtRating.Text = reader["rating"].ToString();
}
conn.Close();
}
}
}
catch (Exception)
{
throw;
}
}
Hope this is what you want if my assumption is correct.
SELECT FirstName, LastName, Player_Attributes.overall_rating
FROM Player JOIN Player_Attributes
ON Player.Player_api_id= Player_Attributes.Player_api_id
I hope your overall logic is wrong - playersListBox_SelectedIndexChanged() in this change event you needs to bind all the values.
for example.
txtRating.Text = queryresultobject.overall_rating.value;
txtName.Text = queryresultobject.Name;
Like above onchange event you needs to bind the values. First go through how to bind values onchange of dropdown in asp.net
This link will give you more clarity on how to implement
Edited - changed join logic

C# Oledb update data in application

So i have got a form in which there are two sections one to add and one to delete.
But the problem is when i add data and after which when i check the combobox associated with delete section i can see all previous data except the one which i just added. So i need some kind of solution to refresh and re get everything into combobox as soon as i click Add button but no luck the latest data wont show.
Code for add button:
private void btnAddSubj_Click(object sender, EventArgs e)
{
OleDbDataReader cmd = ad.select("SELECT TOP 1 ID FROM subjects WHERE ID = " + int.Parse(txtSubjID.Text));
if (cmd.Read())
{
MessageBox.Show("Subject ID you entered is taken, please select a different one");
}
else
{
ad.insert("insert into subjects (`ID`,`subjectName`) values(" + int.Parse(txtSubjID.Text) + ",'" + txtSubjName.Text + "')");
}
populateComboBoxSubjName();
}
Here ad is associated to class which i created and contains all the methods for insert,select,delete,update.
code for populateComboBoxSubjName:
private void populateComboBoxSubjName()
{
comboBoxSubjName.Items.Clear();
OleDbDataReader cmd = ad.select("SELECT * FROM subjects");
while (cmd.Read())
{
for (int f = 0; f < cmd.FieldCount; f+=2)
{
string data = (cmd.GetValue(f).ToString() + "-" + cmd.GetValue(f + 1).ToString());
comboBoxSubjName.Items.Add(data);
}
}
}
Button Delete Code:
private void btnDeleteSubj_Click(object sender, EventArgs e)
{
string selected = this.comboBoxSubjName.GetItemText(this.comboBoxSubjName.SelectedItem);
string[] idToDelete = selected.Split('-');
ad.delete("DELETE FROM subjects WHERE ID=" + int.Parse(idToDelete[0]));
}
I was trying to perform sql queries using another class (i created one and coded all the queries and connections with different methods for each like insert,delete,select) so i wouldnt need to write whole command again and again but for some reason it didnt work. I had to write every command again and again and that worked perfectyl.

My dataGridView isnt updating when i have edited a row of values in a seperate form

I have a dataGridView within a MainForm that is listing all the relevant data into it when the form loads.
When i want to go to edit a row. I select it and press edit, it then loads an EditForm. Here i can edit the data and save.
The information has been successfully edited and saved but the dataGridView isnt updating.
Is there an autoRefresh property i have not seen or a way to refresh it when closing the edit form?
MainForm
private void EditAdminBtn_Click(object sender, EventArgs e)
{
EditAdminForm Admin = new EditAdminForm();
Admin.idTxt.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
Admin.usernameTxt.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
Admin.firstnameTxt.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
Admin.surnameTxt.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
Admin.emailTxt.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();
Admin.statusCombo.Text = this.dataGridView1.CurrentRow.Cells[6].Value.ToString();
Admin.ShowDialog();
}
public void MainForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'student_CBDataSetAdmin.Admin' table. You can move, or remove it, as needed.
this.adminTableAdapter.Fill(this.student_CBDataSetAdmin.Admin);
}
EditForm
private void SaveBtn_Click(object sender, EventArgs e)
{
//SQL Connection and SQL for updating admin information
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
SqlDataAdapter sda3 = new SqlDataAdapter("UPDATE Admin set Admin_Username='" + this.usernameTxt.Text + "' , Admin_FName='" + this.firstnameTxt.Text + "' , Admin_SName='" + this.surnameTxt.Text + "' , Admin_Email='" + this.emailTxt.Text + "', Admin_Status='" + this.statusCombo.Text + "' WHERE Admin_ID='" + this.idTxt.Text + "'", con);
DataTable dt3 = new DataTable();
sda3.Fill(dt3);
MessageBox.Show("Information Successfully Updated!");
dt3.Clear();
this.Close();
}
THIS IS WHAT IT LOOKS LIKE, GRIDVIEW SOURCE AND BINDING AT THE BOTTOM
The problem is that you are not sending any reference to a databound object or whatever, you are copying the values from the datagridView into the popup, and then you are not doing anything with it.
You need to either return the dataTable when you are closing the popup, or manually call a refresh of your dataAdapter. This second option is easier though it requires one more trip to the database.
at the end of your EditAdminBtn_Click add`
EDIT: As per your screenshot, I see that you use a bindingSource. Once you've refreshed your dataTable you can reset the bindings
this.adminTableAdapter.Fill(this.student_CBDataSetAdmin.Admin);
AdminBindingSource.ResetBindings(false);

Database update only works SOME of the time [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Data not writing out to Database
I'm trying to update a bit field in my database on a checkbox's checkedchanged event. When it gets checked, it sends a 1. When it is unchecked, it sends a 0. Now I'm not sure why, but these changes only get saved SOME of the time. Would this have anything to do with the "!IsPostBack" ?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
dataSet = new DataSet();
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
}
protected void CheckBoxProcess_CheckedChanged(object sender, EventArgs e)
{
bool update;
string checkedString = "UPDATE SecureOrders SET processed = 1 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
string uncheckedString = "UPDATE SecureOrders SET processed = 0 WHERE fName LIKE '%" + DefaultGrid.SelectedRow.Cells[2].Text + "%' AND lName LIKE '% " + DefaultGrid.SelectedRow.Cells[3].Text + "%'";
CheckBox cb = (CheckBox)sender;
GridViewRow gvr = (GridViewRow)cb.Parent.Parent;
DefaultGrid.SelectedIndex = gvr.RowIndex;
update = Convert.ToBoolean(DefaultGrid.SelectedValue);
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
{
connection.Open();
SqlCommand checkedCmd = new SqlCommand(checkedString, connection);
SqlCommand uncheckedCmd = new SqlCommand(uncheckedString, connection);
if (cb.Checked == true)
{
checkedCmd.ExecuteNonQuery();
}
else
{
uncheckedCmd.ExecuteNonQuery();
}
connection.Close();
}
I would recommend setting "EnableViewState" to false on your DataView, and then moving the code from the if (!IsPostBack) section to your page's Pre_Init event. I think that will solve your problem and possibly also help your postbacks go faster.
The !IsPostBack is not your issue, whether or not I like the pattern. The postback event handler is a mess, however.
You have left open a potential SQL injection hole by concatenating strings rather than using parameters. Even if you have to write a sproc and pass in a comma separted list, you are better off than the code you have.
Your decision point is one whether or not a value is set to 1 or 0, yet you branch code on the point of deciding which of two strings to run (one will always be created, consuming cycles, yet NEVER run).
You are creating two command objects, one of which will NEVER be used.
You can determine where things are going wrong by stepping through the code with a wide variety of test cases. Eventually you will hit the one that triggers the issue you have.
A better option would be to separate out the SQL update code into its own routine and send the parameters in. This will reduce the number of moving parts. The only thing that should be in the main event handler (and this can be argued) is the grabbing of the variables from the Grid.
If it were me, I would also consider using the key value for my update statement, lest you have two James Smith's in the database, both which are now processed.
As for candidates why it updates some times and not others? Could very well be that you are ending up with the wrong selected row for some reason. As I don't have a copy of your code to see all the permeatations, I can only guess.

Categories

Resources