There is a textbox which searches the value from the Gridview. When the value displays then Every time I click Edit it goes to the first Index Row of the Gridview. I want to only edit the row which has been searched by ID.
For example if I search a value that is in row 8. It displays row 8 which is fine but when I click edit it goes to first row again. Why is this happening?
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
protected void BindGridView()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory", con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("select * from tblInventory where (Part like '%" + txtSearch.Text + "%') or (Brand like '%" + txtSearch.Text + "%' )", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox Part = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPart");
TextBox Description = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Qty = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtQty");
DropDownList Brand = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlBrand");
TextBox ItemType = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtItemType");
SqlCommand cmd = new SqlCommand("update tblInventory set Part='" + Part.Text + "',Description='" + Description.Text + "',Qty='" + Qty.Text + "',Brand='" + Brand.Text + "',ItemType='" + ItemType.Text + "' where ID=" + id, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
You need to modify your BindGridView Method, it will take care the problem.
Now when you a search a value in any Row and it displays the results, and when edit is clicked, it will stay on the selected Row.
txtSearch is just the ID of your Search TextBox.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView(this.txtSearch.Text);
}
}
protected void BindGridView(string column1)
{
SqlCommand cmd = new SqlCommand("select * from table1 where (column1 like '%" + txtSearch.Text + "%')", con);
con.Open();
cmd.Parameters.AddWithValue("#column1 ", column1 );
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView(this.txtSearch.Text);
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView(this.txtSearch.Text);
}
Related
So I have written my code but every time i try to execute it it says "exception unhandled System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'" and it always shows it at the line that says da.Fill(dt);
please tell me how to fix it
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The best practice for handling connection objects is to store them in a local variable and dispose them as soon as possible. You don't need to worry overhead opening and closing connections; they are actually managed in a pool and it's very efficient.
You are storing your connection at the class level and not handling the connection properly. If you store it at the class level, it could time out between button clicks, and it's taking up resources the whole time. Close or dipose the connection right away, which will return it to the connection pool.
To fix, follow this sort of pattern:
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
//Get rid of member variable for the connection. Add constant for connection string.
private const string ConnectionString = #"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True";
private void button1_Click(object sender, EventArgs e)
{
//Use using and use a local variable for the connection
using (var con=new SqlConnection(this.ConnectionString))
{
con.Open();
var cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
//Create a new connection each time you need one
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
else if (comboBox1.Text == "EmployeeName")
{
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
your connection property is not intialised.Click button_click to have your connection intialised.or inside Textbox5_textchanged check for connection con.Isopen else intialize connection object again.
I think you shoul initialize connection object first of all.
You can change your code with the below code and pls return result:
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(con == null)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
}
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter da = null;
DataTable dt = new DataTable();
if(comboBox1.Text == "EmployeeID")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else if (comboBox1.Text == "EmployeeName")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else
{
}
dataGridView1.DataSource = dt;
}
Your connection has not been initialized at the time you're textBox5 text has changed. Move it to your constructor.
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I try to update data in grid view. When i press edit button in grid view row data will be fill in other page in relevant control and press update button data will be update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditButton")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Response.Redirect("~/Home.aspx?Id=" + row.Cells[0].Text);
}
}
Destination page code
public partial class Home : System.Web.UI.Page
{
Property p = new Property();
int Id = 0;
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{
BindTextBoxvalues();
}
}
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from tblUsers where Id=" + Id, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtUsername.Text = dt.Rows[0][0].ToString();
txtEmail.Text = dt.Rows[0][1].ToString();
txtDob.Text = dt.Rows[0][2].ToString();
txtPass.Text = dt.Rows[0][3].ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update tblUsers set UserName='" + txtUsername .Text + "',Email='" + txtEmail.Text + "',DOB=" + txtDob.Text + ",Password='" + txtPass.Text + "' where Id=" + Id, con);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
}
Response.Redirect("~/Admin/Home.aspx");
}
}
Error: Input string was not in a correct format.
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{
I have a textbox where I write a word to search in the gridview. The research works well for the first page of my gridview, but when I go to another page the research resets.
Here is my code :
using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "select * from Ressources";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
private void BindData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + ";select * from Ressources", conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
{
...
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView1.EditIndex >= 0)
return;
if ((e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) &&
(e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header))
{
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].Visible = false;
e.Row.Cells[6].Visible = false;
e.Row.Cells[7].Visible = false;
e.Row.Cells[8].Visible = false;
e.Row.Cells[10].Visible = false;
e.Row.Cells[14].Visible = false;
e.Row.Cells[15].Visible = false;
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
...
}
private void AddNewRecord(string URL, string Type_Source, string First_date, string Data, string Crawler_subcategory)
{
...
}
protected void Button1_Click(object sender, EventArgs e)
{
...
}
public void btnSearch_Click(object sender, EventArgs e)
{
string query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
The function used to search the word is named btnSearch_Click().
I would appreciate your help.
Thank you !
I would use a dataview and rowfilter. You could also choose to cache the OriginalDataTable in a sessionvariable.
public partial class WebForm1 : System.Web.UI.Page
{
// Hold the original datatable from database
System.Data.DataTable OriginalDataTable = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridView("");
}
void BindGridView(string searchQuery )
{
GridView1.DataSource = GetSelectionResult(searchQuery);
GridView1.DataBind();
}
private void initialData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString;
string query = "select * from Ressources";
OriginalDataTable = new DataTable();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString))
{
dataAdapter.Fill(OriginalDataTable);
}
}
DataView GetSelectionResult(string searchParam)
{
if (OriginalDataTable == null)
initialData();
if (string.IsNullOrEmpty(searchParam))
return OriginalDataTable.DefaultView;
string rowFilter = string.Format("data like '%{0}%'", searchParam);
return new DataView(OriginalDataTable, rowFilter, "data", DataViewRowState.OriginalRows);
}
protected void Button1_Click(object sender, EventArgs e)
{
BindGridView(TextBox1.Text);
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
//...
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView(TextBox1.Text);
}
}
In the case of caching the datatable into a sessionvariable:
private void initialData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["defaultconnection"].ConnectionString;
string query = "select * from Ressources";
if (Session["datatableinsession"] == null)
{
OriginalDataTable = new DataTable();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString))
{
dataAdapter.Fill(OriginalDataTable);
}
}
else
{
OriginalDataTable = Session["datatableinsession"] as DataTable;
}
}
Regards.
public void btnSearch_Click(object sender, EventArgs e)
{
BindData();
}
Private xxx BindData()
{
if(Viewstate[txt] !==null)
{
string WhereCl= GetWhereClause(txt);
}
string query = "select * from Ressources";
if(!string.IsNullOrEmpty(WhereCl))
{
query =query + WhereCl;
}
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Private string GetWhereClause(string txt)
{
string where = where data like'%" + txt+ "%'";
}
Call this binding method on paging also .
Hope this helps ..
isn't it faster to just save the search parameter in session, check if it is inside and search it again (since it seems your text data isn't saved)
Declare separate method as
private void Search()
{
string query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Call Search() on page index chenging as
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Search();
}
And you can call the same method on search button click.
public void btnSearch_Click(object sender, EventArgs e)
{
Search();
}
Create only one Method to Bind The Data as below:
private void BindData()
{
string query = "";
if (txtSearch.Text != "" && txtSearch.Text != string.Empty) {
query = "select * from Ressources where data like'%" + txtSearch.Text + "%'";
} else {
query = "select * from Ressources";
}
SqlCommand cmd = new SqlCommand(query);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Thats all
I have a gridview.
I am trying to edit it, but value is not getting updated.
My Code:
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindGrid();
GridView1.EditIndex = -1;
}
catch (Exception ex)
{
}
finally
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
Please let me know the point where i am making mistake.
use BindGrid() inside Page.IsPostBack as follows on Page_Load event
if(!Page.IsPostBack)
{
BindGrid();
}
Edit 1
I think the following line should work
BindGrid();
GridView1.EditIndex = -1;
As it is not working see is there any error in the catch block.
catch (Exception ex)
{
Response.Write(ex.Message);
}
See weather there is some error or not?
You can try like this...becuase...when you click on edit button your pageload event is called first....and on pageload you bind the gridview again...so its edit index is lost because it binded again...and it set edit index to -1 each and everytime...
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
}
Edit1: OP After Update Edit Mode Doesnt goes..
You Have to Set gridview Edit index before Its binding like below....
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='" + eName + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;//Put this line Before the Binding of GridView
BindGrid();
}
I am trying to implement a button_click event in C# such that if the button is pressed, the gridview is filled with the query results but am getting the above error.
This is the code:
public partial class Pages_Managingpayment : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Load();
}
}
protected void Load() {
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}
protected void SearchButton_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from users", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox pass = (TextBox)GridView1.Rows[e.RowIndex].FindControl("Password");
TextBox usernames = (TextBox)GridView1.Rows[e.RowIndex].FindControl("username");
TextBox usertypes = (TextBox)GridView1.Rows[e.RowIndex].FindControl("usertype");
con.Open();
SqlCommand cmd = new SqlCommand("update users set User_Type='" + usertypes.Text + "',Username='" + usernames.Text + "' where password='" + passwords + "'", con);
cmd.ExecuteNonQuery();
con.Close();
//.ForeColor = Color.Green;
//lblresult.Text = username + " Details Updated successfully";
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindEmployeeDetails();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["UserId"].ToString());
string passwords = GridView1.DataKeys[e.RowIndex].Values["password"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from users where password='" + passwords + "'", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Red;
//lblresult.Text = username + " details deleted successfully";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox usertypes = (TextBox)GridView1.FooterRow.FindControl("usertype");
TextBox usernames = (TextBox)GridView1.FooterRow.FindControl("username");
TextBox passwords = (TextBox)GridView1.FooterRow.FindControl("password");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into users values('" + usertypes.Text + "','" +
usernames.Text + "','" + passwords.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
// lblresult.ForeColor = Color.Green;
//lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
//lblresult.ForeColor = Color.Red;
//lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
I guess here is an error in the code:
DataSet ds = new DataSet();
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
ds will not contain tables and therefore contain no Table[0]. It would be helpful though if you could break your code down to a few lines in which the error occurs.
In the Load() method you create a new DataSet and try to access it's non-existing table with the code ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());.
Try creating a new DataTable and adding it to the DataSet before binding it the GridView (Example Here).
And also, when you call the Load() method, make the condition if(!IsPostBack) as in:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Load();
}
}
Make sure you check the index before you use table or Row. I have modified your Load method and hope you can modify other places to correct the mistakes.
protected void Load() {
DataSet ds = new DataSet();
if(ds.Tables.Count == 0)
{
// Syntax might be wrong. I am trying to add new table if it is missing.
ds.Table.Add(new Table());
}
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No records on display";
}