How to update data in grid view? - c#

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)
{

Related

How to show the selected value from the drop down list and show it in gridview

I want it to show the selected value from the drop down list and show it on gridview. It is supposed to query from the database using Where to indicate the selected value to show. For example, I select james from the drop down list. It supposes to go to the database and query james row. After that the grid view is supposed to show only one value which james. But now I am having a problem where the grid view show every data that is available in the database.
public partial class Search_Engine : System.Web.UI.Page
{
#region Database
static string HostName = "localhost";
static string DatabaseName = "finalproject";
static string TableName = "truckinfo";
//static string TableBucket = "bucketbrigade";
static string UserName = "root";
static string Password = "";
//--- Used for access to database infomation-----
string ConnStr = "Data Source=" + HostName + ";" +
"Database=" + DatabaseName + ";" +
"User ID=" + UserName + ";" +
"Password=" + Password;
string Qry = "";
MySqlConnection Con;
MySqlCommand Cmd;
MySqlDataReader Rdr;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
using (Con = new MySqlConnection(ConnStr))
{
Con.Open();
using (Cmd = new MySqlCommand("SELECT * FROM truckinfo", Con))
{
using (Rdr = Cmd.ExecuteReader())
{
if (Rdr.HasRows)
{
DropDownList1.DataSource = Rdr;
DropDownList1.DataValueField = "truckplateno";
DropDownList1.DataTextField = "truckplateno";
DropDownList1.DataBind();
}
}
}
}
}
}
private void BindData()
{
DataTable dt = new DataTable();
try
{
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " +
DatabaseName + "." + TableName , Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
Con.Open();
try
{
String getquery;
// String a;
getquery = DropDownList1.Text;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
Cmd = new MySqlCommand(Qry, Con);
Cmd.ExecuteNonQuery();
Con.Close();
BindData();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
You need to get the selected value using SelectedValue of dropdownlist and then query database using this value.
getquery = DropDownList1.SelectedValue;
Also you are using BindData method which will always select all data from database you need to seprate this method so only selected data is bind to gridview.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String getquery;
getquery = DropDownList1.Text;
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM finalproject.truckinfo WHERE truckplateno='" + getquery + "'", Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
You are calling ExecuteNonQuey function which is used to Insert or Update data in database so it will not return any data.
Also when using SqlDataAdapter you don't need to explicitly call
Open and Close function for opening and closing connection.
Change your DropDownlist_SelectedIndexChanged function to the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
DataTable dt = new DataTable();
try
{
Con.Open();
string getquery = DropDownList1.SelectedValue;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
MySqlCommand ddlCMD = new MySqlCommand(Qry, Con);
MySqlDataAdapter msda = new MySqlDataAdapter(ddlCMD);
msda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally{
Con.Close();
}
}

Gridview loses edit index when value is searched

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);
}

how to delete folder from a root folder

I have an application in which I have an upload image page where I upload images and store those images in different folders under image folder and its path in a database. The flow of that goes like this:
user selects file from the system
user add description
user selects department from the drop-down list and according to that selection the image is stored in a different department's folder.
this is my uploadImage.cs page code:
In this page first we check that we have folder under Image/Department folder or not if not than we create folder and store image under that department else if already create that store image under that department
protected void btnSubmit_Click1(object sender, EventArgs e)
{
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["WebGallery"].ConnectionString;
string Description = tbImageName.Text.Trim();
string Priority = lblPriority.Text.Trim();
//Get Filename from fileupload control
string imgName = fileuploadimages.FileName.ToString();
//sets the image path
string imgPath = "Images/Departments/" + "" + ddlDepartment.SelectedValue + "/";
bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
if (!IsExists)
System.IO.Directory.CreateDirectory(Server.MapPath(imgPath));
//then save it to the Folder
fileuploadimages.SaveAs(Server.MapPath(imgPath + imgName));
//Open the database connection
con.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("insert into Images(ImageName, Description, Path, Priority) values (#ImageName, #Description, #Path, #Priority)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("#ImageName", imgName);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#Path", imgPath + imgName);
cmd.Parameters.AddWithValue("#Priority", lblPriority.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
tbImageName.Text = string.Empty;
}
In this page we create,edit,update and delete department. Now when user click on delete button i want to delete that folder so that all the image under that folder will also delete.
My departmentMaste.cs page code:
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Department_Master", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//int id = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
TextBox txtDepartment = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDepartment");
con.Open();
SqlCommand cmd = new SqlCommand("update Department_Master set DepartmentName='" + txtDepartment.Text + "'where ID=" + id, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = id + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Department_Master where ID=" + id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = id + " details deleted successfully";
}
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + id + "')");
}
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtDepartment = (TextBox)gvDetails.FooterRow.FindControl("txtDepartment");
con.Open();
SqlCommand cmd =
new SqlCommand("insert into Department_Master values('" + txtDepartment.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtDepartment.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtDepartment.Text + " Details not inserted";
}
}
}
i hope i am clear to you guys
How can I do that?
update your RowDeleting event.
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Department_Master where id=" + id, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Table[0];
for (int i = 0; i < dt.rows.count; i++)
{
string imgPath = "Images/Departments/" + "" + dt.rows[i]["DepartmentName"] + "/";
bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
if (IsExists)
System.IO.Directory.Delete(Server.MapPath(imgPath),true);
}
con.Close();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Department_Master where ID=" + id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = id + " details deleted successfully";
}
BindEmployeeDetails();
}
For Pop-up message,
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + id + "');");
}
}
}
just make sure "ConfirmationBox" method is right to raise confirm window.
To Delete images from Images Table, you should have reference of Department_Master Table. like a Column named DepartmentID with foreign Key reference into Images table. even whenever you insert records into Images table, also insert respective DepartmentID, once you are done all these stuff, you can run delete command on Images table as
SqlCommand cmd = new SqlCommand("Delete from Images where DepartmentID="+id +"; delete from Department_Master where ID=" + id, con);
Add this code into aspx page
<script type="text/javascript">
function ConfirmationBox(id)
{
return confirm('Are you sure to delete department Id:'+ id +'?' );
}
</script>
Use GetFiles to get the files from directory and use GetParent to get directory from
the image.
string dir = Directory.GetParent(photoPathFromDB).FullName;
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
//do stuff

How to display Image When Value will be True or False in Database

I wonder how to set The Picture box, and it will display 2 Images. On Value True image number 1, on value False, image number 2. I'm a noob in programming... My Record name is "oddal" dataType is "bit"
Here is my Code
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
pokazliste();
}
private void button1_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Insert into Table1 (id,imie) values('" + textid.Text + "','" + textimie.Text + "')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Wpis Wprowadzony","Vindykacja by Brzoska");
cn.Close();
textid.Text = "";
textimie.Text = "";
pokazliste();
}
}
private void pokazliste()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "Select * From Table1";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if (l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
textid.Text = listBox1.SelectedItem.ToString();
textimie.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "" & listBox1.SelectedIndex!=-1 )
{
cn.Open();
cmd.CommandText = "delete from Table1 where id='" + listBox1.SelectedItem.ToString() + "' and imie= '" + listBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Uaktualniony", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textid.Text != "" & textimie.Text != "")
{
cn.Open();
cmd.CommandText = "Update Table1 set id='" + textid.Text + "', imie= '" + textimie.Text + "'Where id'" + textid.Text + "'and imie= '" + textimie.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Wpis Usuniety", "Vindykacja by Brzoska");
pokazliste();
textid.Text = "";
textimie.Text = "";
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\MSI\Documents\Visual Studio 2010\Projects\Baza z własnymi batonami\Baza z własnymi batonami\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cn.Open();
cmd.CommandText = "SELECT oddal FROM TableName WHERE (Your = Condition)";
dr = cmd.ExecuteReader();
if dr.Read()
{
if dr("oddal")
{
//Set picture box to image 1
}
else
{ //Set picture box to image 1
}
}
cn.Close();
Make sure to specify your condition in the SELECT. Also, for the future, assign meaningful names to the controls. Instead of button1, say btnInsert...

System.IndexOutOfRangeException : Cannot find table 0

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";
}

Categories

Resources