i am trying to update Gridview by Code behind file.
on clicking the update button i get "Incorrect syntax near the keyword set
The tableName is showing properly
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label l=GridView1.Rows[e.RowIndex].FindControl("ID") as Label;
TextBox question=GridView1.Rows[e.RowIndex].FindControl("questions") as TextBox;
TextBox answer=GridView1.Rows[e.RowIndex].FindControl("answer") as TextBox;
TextBox option1=GridView1.Rows[e.RowIndex].FindControl("op1") as TextBox;
TextBox option2=GridView1.Rows[e.RowIndex].FindControl("op2") as TextBox;
TextBox option3=GridView1.Rows[e.RowIndex].FindControl("op3") as TextBox;
TextBox option4=GridView1.Rows[e.RowIndex].FindControl("op4") as TextBox;
SqlDataSource1.UpdateCommand = "update " + tableName + " set [questions]='" + question.Text + "',[answer]='" + answer.Text + "',[op1]='" + option1.Text + "',[op2]='" + option2.Text+"',[op3]='"+option3.Text+"',[op4]='"+option4.Text+"' where ID="+l.Text;
//GridView1.DataBind();
}
I have initialized tableName variable inside Page_Load event handler
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
According to your comment, here's what your Page_Load method look like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
}
That will make tableName empty when GridView1_RowUpdating is executed, so the value of SqlDataSource1.UpdateCommand will become update set [questions]=... instead of update J2EE_testMaster set [questions]=.... You need to set the tableName value outside of if (!IsPostBack) block:
protected void Page_Load(object sender, EventArgs e)
{
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
tableName = "J2EE_testMaster";
}
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
}
}
}
You also need to parameterize your SQL query to avoid SQL Injection.
Related
I have a website where the admin can delete or add new gridview. For example, if i currently have gridview for giordano products and wanted to change the brand to bossini products. When the admin clicked edit button, the whole gridview and code for giordano products should be removed and if i'm already in update mode and changed the brand name to "bossini" and clicked update, It should add new gridview and code for bossini products.
Now here's the problem. When i do click the edit button, it will remove the whole gridview code but the gridview itself still appears in the website. I finally know that i need to refresh the page but i don't know the best way yet. I have tried Response.Redirect("urls") in GuitarBrandsGridView_RowEditing, but it is not working and it is giving me an exception. It works for GuitarBrandsGridView_RowDeleting tho. I just assumed that maybe it would work for my edit button but it failed.
My goal is, when i click the edit button in gridview, the whole webpage should refresh and then proceed to update mode. Hope this makes sense.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
bindgridviewguitarbrands();
BindGridViewDataList.GetItemsLoad();
}
}
//Start of Gridview Code for Guitar Brands
private void bindgridviewguitarbrands()
{
con1.Open();
cmd1.CommandText = "SELECT * FROM [guitarBrands]";
cmd1.Connection = con1;
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(ds1);
con1.Close();
GuitarBrandsGridView.DataBind();
}
protected void GuitarBrandsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
Button button = (Button)e.Row.FindControl("GuitarBrandsGridViewBtnDelete");
button.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + name + "' )");
}
}
protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
con1.Open();
cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd1.Connection = con1;
int a = cmd1.ExecuteNonQuery();
con1.Close();
if (a > 0) {
bindgridviewguitarbrands();
}
Response.Redirect("~/Pages/OverviewGuitarData.aspx");
}
protected void GuitarBrandsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GuitarBrandsGridView.EditIndex = e.NewEditIndex;
string id = GuitarBrandsGridView.DataKeys[e.NewEditIndex].Value.ToString();
Label name = (Label)GuitarBrandsGridView.Rows[e.NewEditIndex].FindControl("lblName");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
bindgridviewguitarbrands();
Response.Redirect("~/Pages/OverviewGuitarData.aspx");//this one is not working
}
// row update event
protected void GuitarBrandsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// find student id of edit row
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
// find updated values for update
TextBox type = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtType");
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
TextBox image = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtImage");
cmd1 = new SqlCommand("UPDATE [guitarBrands] SET Type = '" + type.Text + "', Name = '" + name.Text + "', Image = '" + image.Text + "' WHERE ID = " + id, con1);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text, ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
// cancel row edit event
protected void GuitarBrandsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("txtName");
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text,ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
you need not refresh whole page
GuitarBrandsGridView.DataSource = ds1
GuitarBrandsGridView.DataBind();
then will update new data
Response.Redirect("http://localhost:14999/Home/Index");
Where you want your page to refresh you need to give full path of the page it will reload that page.
I hope it will work coz its working for me
I am facing a problem in my form. There are two text field and then there is drop-down menu, which link to a database.
When I click on the drop down menu, my two text fields are getting empty.
protected void OnChange_Acdemics(object Sender, EventArgs e)
{
DropDownList list = (DropDownList)Sender;
string value = (string)list.SelectedValue;
// degrees_dropdown.Visible = true;
try
{
// String query = "SELECT Degree_types.detail,Degree_Detail.GPA FROM Degree_Detail INNER JOIN Degree_types ON Degree_Detail.Degree_tilte = Degree_types.Degree_title where Degree_types.degree_type = '" + value + "';";
String query = "Select detail from Degree_Detail where id=" + int.Parse(value) + ";";
Dt = dbComm.GetDataTable(query);
Degree_Selection.DataTextField = "detail";
// Degree_Selection.DataValueField = "GPA";
Degree_Selection.DataSource = Dt;
Degree_Selection.DataBind();
}
catch (Exception ex)
{
}
}
You need to take care of this by using Page.IsPostBack:
if(!Page.IsPostBack)
{
// load page
}
else
{
// check input values and set it again
}
For example when the same First Name with different Last Name
to filter name and write in Last Name filter, but keeping the names filter.
Example whith a textbox:
Connection:
public void read_data(string query, ref DataSet principal, string tabla)
{
try
{
string cadena = "Server=0.0.0.0; Database=DB; Uid=user; Pwd=pass";
MySqlConnection cn = new MySqlConnection(cadena);
MySqlCommand cmd = new MySqlCommand(query, cn);
cn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(principal, tabla);
cn.Close();
}
catch (Exception ex)
{
}
}
Load dataGridView:
private void Form1_Load(object sender, EventArgs e)
{
this.read_data("Select * From reg", ref result, "reg");
this.filtro = ((DataTable)result.Tables["regi"]).DefaultView;
this.dataGridView1.DataSource = filtro;
}
Event:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
string data_output = " ";
string[] search_word = this.textBox1.Text.Split(' ');
foreach (string word in search_word)
{
if (data_output.Length == 0)
{
data_output = "(FirstName LIKE '%" + word + "%')";
}
else
{
data_output += "(FirstName LIKE '%" + word + "%')";
}
}
this.filtro.RowFilter = data_output;
}
Here is one approach to achieve your requirement.
Create a common function to call from both the text boxes as below
private string GetFilterExpression(string sFilterExprValue, string sFilterFieldName)
{
string sFilterExpr = "";
string[] search_word = sFilterExprValue.Split(' ');
foreach (string word in search_word)
{
if (sFilterExpr.Length == 0)
{
sFilterExpr = "(" + sFilterFieldName + " LIKE '%" + word + "%')";
}
else
{
sFilterExpr += " AND (" + sFilterFieldName + " LIKE '%" + word + "%')";
}
}
return sFilterExpr;
}
Call the common function from key up event of both the text boxes as shown below;
Text Box 1 with First Name filter
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
// Text box to enter Firstname filter
string sFilter = GetFilterExpression(this.textBox1.text, "FirstName");
if (!this.textBox2.text)
{
string sLastNameFilter = GetFilterExpression(this.textBox2.text, "LastName");
if (!String.IsNullOrEmpty(sLastNameFilter)) // Concat the Last Name Filter
sFilter += String.IsNullOrEmpty(sFilter) ? "" : " AND " + sLastNameFilter;
}
this.filtro.RowFilter = sFilter;
}
Text Box 2 with Last Name filter
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
// Text box to enter Lastname filter
// Assume the field storing last name is 'Lastname'
string sFilter = GetFilterExpression(this.textBox2.text, "LastName");
if (!this.textBox1.text)
{
string sFirstNameFilter = GetFilterExpression(this.textBox1.text, "FirstName");
if (!String.IsNullOrEmpty(sFirstNameFilter))
sFilter += String.IsNullOrEmpty(sFilter) ? "" : " AND " + sFirstNameFilter;
}
this.filtro.RowFilter = sFilter;
}
Hope this helps and mark it as so if this addresses your issue.
Edited: to update the textBox2_Keyup event to concatenate any filter expression typed into textBox1
I am using the following function to populate my ComboBox
public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName, string AValue, string Adisplay)
{
string Value = AValue;
string display = Adisplay;
using (var CONN = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Test.accdb;"))
{
CONN.Open();
DataTable dt = new DataTable();
try
{
OleDbCommand cmd = new OleDbCommand(Query, CONN);
OleDbDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (OleDbException e)
{
MessageBox.Show(e.ToString());
return;
}
DropDownName.DataSource = dt;
DropDownName.ValueMember = Value;
DropDownName.DisplayMember = display;
}
}
And I'm calling it in the load form:
private void Form1_Load(object sender, EventArgs e)
{
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
}
2.After that I'm using the same Function in the event of Selectedindexchanged event to populate another ComboBox:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
And for the population of the two combobox's everything works fine however here is the issue
I have two combobox's as shown in the pic :
So te first combobox ( country ) loaded in the form perfectly
but what I'm trying to do is to make the the second combobox ( the state ) being selected from Database only when I select the country but what happen is that the code runs and the second combobox goes and select from database whatever is the selected index in the first combo is as the pic shows
So what I basically want to do is to make the second Combo being populated only when I select an index from the first combobox.
Put your code in SelectionChangeCommitted Instead of SelectedIndexChanged
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
I think your problem is being cause because the population of the first combo box fires the event to populate the second one. One way around it is to have something like the following in comboBox1_SelectedIndexChanged(object sender, EventArgs e).
if (comboBox1.Text == string.Empty) { return; }
If that doesn't work try using the "SelectedIndex > 0" or "SelectedValue" property.
As a point of note your code is potentially prone to SQL injection attacks, if anyone was able to modify your combo-box items.
You need to identify wether the item is really changed from Combobox or not by using SelectedIndex property.
Try This:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex >= 0)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Change your following method to
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != -1 && comboBox2.SelectedIndex != -1 )
{
FillDropDownList("select StateCode,StateName from States Where CountryCode = '" + comboBox1.SelectedValue + "'", comboBox2, "StateCode", "StateName");
}
}
Before submitting for query the DB you validate your both comboboxes. Check for any selected item.
Thanks
Srikanth
Remove the SelectedIndexChanged event handler before calling FillDropDownList method, and re-apply it after the ComboBox is populated.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
FillDropDownList("select CountryCode,Countryname from Countries", comboBox1, "CountryCode", "Countryname");
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
I have 2 tables 'contract' and 'customer', they have fk relationship. I drag 'contact' onto form then do so with 'customer', both are details type. The data of 2 tables are shown on form accordingly. The problem is when I modify then click save button only data of 'contract' table is updated.
private void button67_Click(object sender, EventArgs e)
{
if (textBox81.Text == "")
{
MessageBox.Show("you must choose table name");
}
if (textBox81.Text != "")
{
connect();
cmd = new OleDbCommand("select * from " + textBox81.Text + " ", conn);
ds = new DataSet();
dp = new OleDbDataAdapter(cmd);
dp.Fill(ds,""+textBox81.Text+"");
cm = (CurrencyManager)this.BindingContext[ds];
textBox79.DataBindings.Add("text",ds,""+textBox81.Text+""+".ProdS_name");
textBox80.DataBindings.Add("text", ds, "" + textBox81.Text + "" + ".rate");
}
}
private void button58_Click(object sender, EventArgs e)
{
cm.Position++;
}
private void button59_Click(object sender, EventArgs e)
{
cm.Position= cm.Count - 1; ;
}
private void button61_Click(object sender, EventArgs e)
{
cm.Position=0;
}