Okay, so I am learning grid views and list views... Currently what I have is a working grid view.
The following code is as follows:
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName.CompareTo("Delete") == 0)
{
int newIndex = Convert.ToInt32(e.CommandArgument);
string studentEmail = GridView1.Rows[newIndex].Cells[1].Text;
AccessDataSource1.DeleteCommand = "DELETE FROM [CoursesTaken] WHERE [CourseID] = '" + studentEmail + "'";
AccessDataSource1.Delete();
AccessDataSource1.DataBind();
}
}
This works perfect for me. So I made a few other buttons for it and decided to move onto the list view and learn it. I cannot figure out why my delete button will not work. I currently can only make an update button. So, this is the code that I have so far
string StudentIDLabel = ((Label)(e.Item.FindControl("StudentIDLabel"))).Text.Trim();
string CourseIDLabel = ((Label)(e.Item.FindControl("CourseIDLabel"))).Text.Trim();
string GradeLabel = ((Label)(e.Item.FindControl("GradeLabel"))).Text.Trim();
AccessDataSource1.DeleteCommand = "DELETE FROM [CoursesTaken] WHERE [StudentID] = '" + StudentIDLabel + "' AND [CourseID] = '" + CourseIDLabel + "' AND [Grade] ='" + GradeLabel + "'";
AccessDataSource1.Delete();
AccessDataSource1.DataBind();
I thought it might by how my SQL statement was and I have changed it around a lot. But As it is now I get a parameter error. I am assuming it might be something isn't passing through correctly..
So I changed my SQL delete statement to
AccessDataSource1.DeleteCommand = "DELETE FROM [CoursesTaken] WHERE [StudentID] = '" + StudentIDLabel + "'" + CourseIDLabel + "'" + GradeLabel + "'";
This gives me the error :
Syntax error (missing operator) in query expression '[StudentID] = 'aaalshehri#mail.usi.edu'CS 402'A''."
StudentID is the first column, follower by CourseID and then Grade.
I am just really struggling with this and maybe a little guidance from someone not as green as I am would be appreciated very much.
Thanks!
Maybe StudentIDLabel, CourseIDLabel, GradeLabel are NULL.
string StudentIDLabel = ((Label)(e.Item.FindControl("StudentIDLabel"))).Text.Trim();
string CourseIDLabel = ((Label)(e.Item.FindControl("CourseIDLabel"))).Text.Trim();
string GradeLabel = ((Label)(e.Item.FindControl("GradeLabel"))).Text.Trim();
You need to show us the whole method/event where you are doing this, so that we may see:
string StudentIDLabel = ((Label)(e.Item.FindControl("StudentIDLabel"))).Text.Trim();
string CourseIDLabel = ((Label)(e.Item.FindControl("CourseIDLabel"))).Text.Trim();
string GradeLabel = ((Label)(e.Item.FindControl("GradeLabel"))).Text.Trim();
AccessDataSource1.DeleteCommand = "DELETE FROM [CoursesTaken] WHERE [StudentID] = '" + StudentIDLabel + "' AND [CourseID] = '" + CourseIDLabel + "' AND [Grade] ='" + GradeLabel + "'";
AccessDataSource1.Delete();
AccessDataSource1.DataBind();
--EDIT--
You need to have the index of the button. So in the aspx code add this in the CommandArgument of the button to get the index:
CommandArgument='<%# Container.DataItemIndex %>'
In code-behind we can now get the labels using this:
Label StudentIDLabel = ListView1.Item[e.CommandArgument].FindControl("StudentIDLabel");
Label CourseIDLabel = ListView1.Item[e.CommandArgument].FindControl("CourseIDLabel");
Label GradeLabel = ListView1.Item[e.CommandArgument].FindControl("GradeLabel");
AccessDataSource1.DeleteCommand = string.Format("DELETE FROM [CoursesTaken] WHERE [StudentID] = '{0}' AND [CourseID] = '{1}' AND [Grade] = '{2}'", StudentIDLabel.Text, CourseIDLabel.Text, GradeLabel.Text)
AccessDataSource1.Delete();
AccessDataSource1.DataBind();
If Student Id is unique the you should be able to do
string sql= string.Format("DELETE FROM [CoursesTaken] WHERE [StudentID] ={0}",
StudentIDLabel);
AccessDataSource1.DeleteCommand = sql;
note integer dont need quotes.
Related
I am trying to read an integer from a SQL Server database by text in comboboxes.
I get a "Syntax error" "near" my Table name "Seeweg". The debugger does not highlight the line, where the error happens.
The column with the value I like to get is named seadistance. The other columns, by which to sort are start and ziel.
They get sorted by the values written in the comboboxes.
To reproduce this procedure I inserted the code into a class and called the instance by a button named btnSea.
I already searched for similar problems, but I could not find any syntax errors concerning the string implementation. The column names are correct.
//The Button
private void btnSea_Click(object sender, EventArgs e)
{
Entnehmen CO2 = new Entnehmen();
int Dist = CO2.Werte("Seeweg", "start", "ziel", "seadistance", comboSeaOrig.Text, comboSeaDest.Text);
MessageBox.Show(Dist.ToString());
}
//The class
class Entnehmen
{
public int Werte(string Tabelle, string Reihe1, string Reihe2, string Wertereihe, string WertReihe1, string WertReihe2)
{
int Wert = 0;
string myConnection = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection myConn = new SqlConnection(myConnection))
{
myConn.Open();
SqlCommand SelectCommand = new SqlCommand("SELECT '" + Wertereihe + "' FROM '" + Tabelle + "' WHERE '" + Reihe1 + "' = '" + WertReihe1 + "' AND '" + Reihe2 + "' = '" + WertReihe2 + "' ; ", myConn);
Wert = (int)SelectCommand.ExecuteScalar();
}
return Wert;
}
}
}
I expect the value to be given back. Before that happens, I get the error:
Incorrect syntex near 'Seeweg'
Where is the syntax mistake? Any help is appreciated =)
You are generating something like:
SELECT 'seadistance' FROM 'Seeweg' WHERE 'start' = 'aa' AND 'ziel' = 'bbb'
This is not a valid T-SQL statement. Correct your quotes in columns and tables variables.
This is a suggestion of how you can write your T-SQL statemant based on your code:
SqlCommand SelectCommand = new SqlCommand("SELECT " + Wertereihe + " FROM " + Tabelle + " WHERE " + Reihe1 + " = '" + WertReihe1 + "' AND " + Reihe2 + " = '" + WertReihe2 + "' ; ", myConn);
I have made a post form where "professors should enter their username and password to be able to post,and I don't get any error about it.
but when I run it, even if I enter the right username and password, it would always just do the "else" command.
Here's my code
protected void Button9_Click(object sender, EventArgs e)
{
string postname = this.Postuser.Text;
string postpass = this.Postpass.Text;
string posttitle = this.TOP.Text;
string postbody = this.BOP.Text;
string sqlstr2 = "select * from professors WHERE pname='" + Postuser + "' AND ppass='" + Postpass + "'";
DataTable dt1 = DBFunction.SelectFromTable(sqlstr2, "DBS.accdb");
if (dt1.Rows.Count > 0)
{
string sqlpost2 = "insert into post2(Professor,Title,Body)";
sqlpost2 += "value('" + postname + "','" + posttitle + "','" + postbody + "')";
DBFunction.ChangeTable(sqlpost2, "DBS.accdb");
}
else
this.Label1.Text = "Posting on this wall is only allowed for profesors and it seems that you're not one";
DataList1.DataBind();
}
In the following line of code, you are trying to concatenate PostUser and PostPass controls instead of their text properties
The following code should be changed:
string sqlstr2 = "select * from professors WHERE pname='" + Postuser + "' AND ppass='" + Postpass + "'";
Update your code like this to postname and postpass variables which are holding text values of user and password
string sqlstr2 = "select * from professors WHERE pname='" + postname + "' AND ppass='" + postpass + "'";
Note: Your code in vulnerable to sql injection attacks so you must use parameterized query
I'm having problem with regards to update my database when I remove a row/s in my datagrid.
I tried using RowsRemoved event but it returns me an error that there is no value in the row deleted.
So when I try searching I have come to this similar problem, all similar problems I have found so far is by adding or subtracting a certain number (like + 1 or - 1). So I matched the code with my parameters.
private void dataGridSales_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Server=" + ip + "," + port + "; Database=records; User ID=" + sqlid + "; Password=" + sqlpass + ""))
{
conn.Open();
int addqty = Convert.ToInt32(dataGridSales.SelectedRows[0].Cells[1].Value.ToString());
string part = dataGridSales.SelectedRows[0].Cells[5].ToString();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Quantity = [Quantity] + '" + addqty + "' WHERE [Part No.] = '" + part + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
The problem is, it did not update my database. I also tried this in my SQL
Quantity = Quantity + '" + addqty + "'
Quantity += '" + addqty + "'
Im using SQL Server 2014
This is the value of the addqty and part at the breakpoint
This are my datagridview columns. ColumnIndex = 5 is where the part value, and RowIndex is the selected row.
EDIT:
I have solve the issue. It was a minor mistake that I wasn't checking the syntax correctly (even there are no errors shown).
string part = dataGridSales.SelectedRows[0].Cells[5].ToString();
Forgot to add .Value
string part = dataGridSales.SelectedRows[0].Cells[5].Value.ToString();
Quantity = Quantity + '" + addqty + "'
You define addqty as an int but use it as a string in the SQL. Remove the single quotes to use the value as a number rather than text.
Quantity = Quantity + " + addqty + "
try to replace dataGridSales.SelectedRows[0].Cells[1].Value.ToString() anddataGridSales.SelectedRows[0].Cells[5].ToString(); by
dataGridSales.SelectedRows[e.RowIndex].Cells[1].Value.ToString();
dataGridSales.SelectedRows[e.RowIndex].Cells[5].ToString();
I am trying to update an Access database with information I have passed to a [WebMethod] from multiple txtbox's on a website.
[WebMethod]
public string changePersonalInfo(string email, string name, string id, string address, string contactDetails, string password, string question, string answer, string loggedInEmail)
I am passing all information to it weather it has a value or not.
if (email != "") //Wont execute if there is no value
{
cmd.CommandText = #"UPDATE BuyerInfo SET [emailAddress] = '" + email + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (name != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [name] = '" + name + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
if (id != "")
{
cmd.CommandText = #"UPDATE BuyerInfo SET [id] = '" + id + "' WHERE (emailAddress = '" + loggedInEmail + "')";
}
//etc. It goes on for a few more.
cmd.ExecuteNonQuery();
conn.Close();
The problem is when I run the website it only updates the data from the last txtbox on the website (so in other words the last variable that has a value). How do I fix this, or if there is maybe a better way to do it.
P.S Keep in mind I am new to Web Services.
Thanx
I use mysql as database where I store my data.
I have a windows form with textboxes radiobuttons, comboboxes and more; where people give personal information about themselves like (first name, last name, sex, date birthday, phone, father name and more like this). (40 fields total)
I want to do a search button. With this button I want to fill some fields and after I push the search button a new window be opened containing all people with same personal information. I achieved to do a search button for one field (for example searching only by name).
But I have a problem when I select to search with more than one fields. For example I select to search all people who have name:Chris, Nickname:Dung, sex:Male, Birth_Country:UK and other but when I push search it gives back a window with irrelevant with the search data. Can someone help me with that?
The code I made for the search button after changes is:
public MySqlDataAdapter da;
public DataSet ds;
public string sTable = "data";
private void anazitisi_button_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
try
{
conn = openconnectio.GetConn();
string radiob = null;
if (radioButton1.Checked == true)
{
radiob = radioButton1.Text;
}
else if(radioButton2.Checked == true)
{
radiob = radioButton2.Text;
}
StringBuilder Query = new StringBuilder("SELECT * FROM data d INNER JOIN country c ON d.id_data = c.id_country WHERE 1=1 ");
if (!String.IsNullOrEmpty(textBox1.Text))
Query.Append(" AND name like '" + textBox1.Text + "'");
if (!String.IsNullOrEmpty(textBox2.Text))
Query.Append(" AND lastname like '" + textBox2.Text + "'");
if (!String.IsNullOrEmpty(radiob))
Query.Append(" AND sex like '" + radiob + "'");
if (!String.IsNullOrEmpty(maskedTextBox1.Text))
Query.Append(" AND birthdate like '" + maskedTextBox1.Text + "'");
if (!String.IsNullOrEmpty(maskedTextBox2.Text))
Query.Append(" AND phone_number like '" + maskedTextBox2.Text + "'");
MySqlDataAdapter da = new MySqlDataAdapter(Query.ToString(), conn);
ds = new DataSet();
da.Fill(ds, sTable);
conn.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dg1 = new DataGridView();
form2.Controls.Add(dg1);
dg1.Dock = DockStyle.Fill;
dg1.Refresh();
dg1.DataSource = ds;
dg1.DataMember = sTable;
form2.Show();
if (conn != null)
{
conn.Close();
}
}
}
My results after search is fine when i comment that code:
(birthdate code) and i dont used as search of course.
//if (!String.IsNullOrEmpty(maskedTextBox1.Text))
// Query.Append(" AND birthdate like '" + maskedTextBox1.Text + "'");
But when i use the (birthdate code) i get us result only a blank row.
I think because the birthdate maskedTextbox have a mask: 00/00/0000
Any suggestion?
Thanks.
I think you should consider three things
1- You may replace OR with And in your query
I mean instead of using
da = new MySqlDataAdapter(
"SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE name like '" + textBox1.Text +
"'OR lastname like '" + textBox2.Text +
"'OR sex like '" + radiob +
"'OR birthdate like '" + maskedTextBox1.Text +
"'OR phone
_number like '" + maskedTextBox2.Text + "' ;", conn);
You may use
da = new MySqlDataAdapter(
"SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE name like '" + textBox1.Text +
"'AND lastname like '" + textBox2.Text +
"'AND sex like '" + radiob +
"'AND birthdate like '" + maskedTextBox1.Text +
"'AND phone_number like '" + maskedTextBox2.Text + "' ;", conn);
2- You have to build your query string based on your text boxes and else seeing if they have any value, something like this:
StringBuilder Query = "SELECT * FROM data INNER JOIN country ON id_data = id_country
WHERE 1=1 ";
if(!String.IsNullOrEmpty(textBox1.Text))
Query.Append(" AND name like '" + textBox1.Text);
....
3- Sql Injection vulnerabilities
oh my God !!! Some programming !!!
where clause must created by and/or ,... other clauses ,
so ,
two solutions exist :
On server Side by Store Procedure by below definition :
you must care by position of AND/OR in below :
CREATE PROCEDURE [dbo].[dbo_Bank_SELByFields]
(
#ID nvarchar(50) = NULL ,
#BankName nvarchar(50) = NULL ,
#BankCode nvarchar(50) = NULL ,
#Address nvarchar(50) = NULL ,
#BranchCode nvarchar(50) = NULL
)
AS
SELECT * FROM dbo.Bank WHERE
(
(#ID IS NULL OR ID = #ID) AND
(#BankName IS NULL OR BankName =#BankName) AND
(#BankCode IS NULL OR BankCode =#BankCode) AND
(#Address IS NULL OR Address =#Address) AND
(#BranchCode IS NULL OR BranchCode =#BranchCode)
) ORDER BY BankCode
//---you know call the Sp . OK?
and other solution in your business layer code :
if you use ORM such as Entity Framework , very easy By IQueryable object, you can use below :
var selectByEnyCondition=(from c in ctx.customer ...);
//---- you must add by below way :
if(!(String.IsNullOrEmpty(txtName.Text)))
{
selectByEnyCondition.Where(.....);
}
if(!String.IsNullOrEmpty(sex))
{
selectByEnyCondition= opportunites.Where(.....);
}
//------
/* **** beacuse you use by ADO.NET technique you should use StringBuilder -->*/
StringBuilder query;
query.add("SELECT * FROM BankTbl WHERE ");
if(!(String.IsNullOrEmpty(txtName.Text))){
query.Add("Name Like {0}",txtName.Text);
//-----now continue for build your criteria
king reguard
bye.....