asp.net grid view edit and delete records - asp.net

i am trying to use a grid view to display items from the database i also want to edit and delete these records then in the grid view, i am using the sample code on asp.net snippets
http://aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspx
it says that The name 'GetData' does not exist in the current context
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default10 : System.Web.UI.Page
{
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
comm = new SqlCommand("select EmployeeID,Name,Password" +
" from Employee");
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "update Employee set Name=#Name," +
"Password=#Password where EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value = EmployeeID;
comm.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "delete from Employee where " +
"EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
}

You are using Old coding so Replace your code with my code..
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default10 : System.Web.UI.Page
{
SqlCommand comm;
SqlConnection connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
connectionString.Open();
comm = new SqlCommand("select EmployeeID,Name,Password from Employee", connectionString);
DataTable dt =new DataTable();
SqlDataAdapter adp= new SqlDataAdapter(comm);
adp.Fill(dt);
connectionString.Close();
GridView1.DataSource =dt;
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
//you should Write this code on Rowupdating and give command name 'update' to link button
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
//start here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
connectionString.Open();
comm = new SqlCommand("update Employee set Name=#Name,Password=#Password where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", EmployeeID);
comm.Parameters.AddWithValue("#Name", Name);
comm.Parameters.AddWithValue("#Password", Password);
comm.ExecuteNonQuery();
connectionString.Close();
GridView1.EditIndex = -1;
BindData();
//end here
}
//you should Write this code on RowDeleting and give command name 'delete' to link button
protected void DeleteEmployee(object sender, EventArgs e)
{
//stat here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
connectionString.Open();
comm = new SqlCommand("delete from Employee where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", lnkRemove);
comm.ExecuteNonQuery();
connectionString.Close();
BindData();
//end here
}
}

Related

How to Get DropDownList selected text and Fill details in GridView and labels based on that in asp.net

I have an ASP.NET site with a SQL Server 2008 database. I want to select the text of a dropdownlist and fill details in GridView and labels based on that, but when I select an item of selected text it does not fill details in GridView and labels.
Notice that my drop downlist is list of months. How can I fix this problem?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class form : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["emp_dbConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void BindEmpGrid()
{
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter();
try
{
SqlCommand cmd = new SqlCommand("select * from shakhes where mah_tadieh=" + ddlEmpRecord.Text + " ", con);
adp.SelectCommand = cmd;
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
grdEmp.DataSource = dt;
grdEmp.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
dt.Clear();
dt.Dispose();
adp.Dispose();
}
}
protected void ddlEmpRecord_TextChanged(object sender, EventArgs e)
{
BindEmpGrid();
}
}
Use SelectedIndexChanged event instead of TextChanged event, and make sure your DropDownList AutoPostBack property is set to "true".
protected void ddlEmpRecord_SelectedIndexChanged(object sender, EventArgs e)
{
BindEmpGrid();
}
Hope it helps.

Object reference not set to an instance of an object while clicking on submit button

I have created a webpage in asp.net
on right hand side I have an ListBox which binds data from database when page loads, Its code at Default.aspx is as below
<asp:ListBox ID="ListOfSql" runat="server"
SelectionMode="Single" DataTextField="sql_name" DataValueField="sql_text"
style="margin-left: 0px; width:auto; height:300px" EnableViewState="true">
</asp:ListBox>
and at default.aspx.cs page its code is
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
I am calling loadSqlList() on page_load so that I can get list from database in ListBox.
Now I have an submit button
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
on default.aspx.cs page submit button's code is
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
Now when I want that on clicking on submit button then text of selected item should appear in textbox which is at left hand side
when I do so I am getting an error page
complete code of default.aspx.cs page is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
System.Data.OracleClient.OracleConnection conn = new OracleConnection("Data Source = orcl; user id=*****;password = *****; unicode = true;");
//OracleConnection conn = new OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=system;password = ravi_123;Unicode=True");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
loadSqlList();
lblLastRefresh.Text = DateTime.Now.ToShortTimeString();
lblDate.Text = DateTime.Now.ToShortDateString();
Response.Cache.SetAllowResponseInBrowserHistory(false);
//============================================= Checking user logged in or not ===================================
//if (Session["txtUserName"] == null)
//{
// Response.Write("<Script Language ='JavaScript'> alert('Session Expired, please login again')</script>");
// conn.Close();
// Response.Redirect("login.aspx");
//}
//============================================= Checking user logged in or not (END) ===================================
//=====================User Ip Tracer =======================
string UserIp = Request.ServerVariables["http_x_forwarded_for"];
string UserHost = Request.ServerVariables["http_X_forwarded_for"];
string userMacAdd = Request.ServerVariables["http_x_forwarde_for"];
if (string.IsNullOrEmpty(UserIp))
{
UserIp = Request.ServerVariables["Remote_ADDR"];
UserHost = System.Net.Dns.GetHostName();
}
LblLoc.Text = UserIp;
LblHostName.Text = UserHost;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.AddHeader("Pragma", "no-cache");
//=====================User Ip Tracer code end =======================
if (!IsPostBack)
{
}
}
protected void onclick_logout(object sender, EventArgs e)
{
conn.Close();
Session.Clear();
Response.Redirect("login.aspx");
}
protected void exportToExcel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql;
sql = txtQuery.Text.ToString();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
//================ User Details Data Insertion in DataBase Ends here ===============
da.Fill(dt);
ExportTableData(dt);
Response.Write("<Script>alert('Ip Locked in DB')</Script>");
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void btnClear_clik(object sender, EventArgs e)
{
txtQuery.Text = string.Empty;
}
private void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename="+ListOfSql.SelectedItem.Text.ToString()+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
// References for this page
// http://forums.asp.net/t/1768549.aspx
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
}
If a selection isn't made then ListOfSql.SelectedItem will be null, and therefore calling .Text on that will result in your error.
Try changing your code to something like this:
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
if(ListOfSql.SelectedItem != null)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
}

get value into query from edit mode in gridview

I have a simple gridview, 2 columns. The first column is a numeric value. The second column is based on a selected value from a drop down list. I have the drop down list working, but when I go to update the table, I get an error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The offending line is 55
Line 53: {
Line 54: string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
Line 55: string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
and here is the code behind for the webform:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string query = "select distinct Unit from vw_KmartBU";
SqlCommand cmd = new SqlCommand(query);
dlBU.DataSource = GetData(cmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
//dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [Business Unit] = #BU where [Annotation Number] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnoNum);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindData()
{
string query = "select [Annotation Number], [Business Unit] as Unit from vw_GridviewSource";
SqlCommand cmd = new SqlCommand(query);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].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;
}
}
}
}
}
}
What I need to do is get the value in first column "Annotation Number" and use it in the where clause of my update. So I would need update vw_GridviewSource set [Business Unit] = 'Accessories' where [Annotation Number] = '123456'
Accessories would have been the selection from the drop down list and 123456 would have been in the text box when I selected that row for editing.
Your gridview is missing DataKeyNames. It may look like:
<asp:GridView ID="gvSummary"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="AnnoNum, MyOtherKey1, MyOtherKey2"
... ... ...
DataKeyNames property is an array of strings. You can find more in MSDN

Extracting data from Table2 to TextArea of Table1

I have designed 2 tables in my aspx page. In table1 there is blank TextArea. In table2 there are fields like FirstName,LastName,Age,DOB and these attributes are already entered in the database. I have entered corresponding symbols for these attributes (for e.g. for Firstname symbol is {F}, for last name symbol is {L} etc..).
My requirement is when i click on a field of Table2 (for e.g. FirstName) it will be displayed on TextArea of table1 like "Hi My Name is {F}".
I have tried myself to do this program, but i did not extract the
symbol of the attribute in my textarea.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=AITPLCP72\SQLEXPRESS;Initial Catalog=Template;Integrated Security=True");
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlDataAdapter adp = new SqlDataAdapter("select field,Symbols from temp2", con);
adp.Fill(ds);
}
}
protected void btnfirstname_onclick(object sender, EventArgs e)
{
Symbol("firstname");
}
protected void btnlastname_onclick(object sender, EventArgs e)
{
Symbol("lastname");
}
protected void btnage_onclick(object sender, EventArgs e)
{
Symbol("age");
}
protected void btndob_onclick(object sender, EventArgs e)
{
Symbol("dob");
}
protected void btnsubmit_Click1(object sender, EventArgs e)
{
string s = TextArea1.InnerHtml;
Response.Redirect("http://localhost:2482/Template1/Default3.aspx?text1=" + s);
}
public void Symbol(string s)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
if (row[0].ToString() == s.ToString())
{
string st = TextArea1.Value;
st += row["Symbols"];
TextArea1.Value = st;
}
}
}
}

Why The Gridview "AutoGenerateEditButton = true "property does not work in run time?

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class ExptGridviewEdit : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataTable dtb;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{
com = new SqlCommand("Select * from tblExpt", con);
da = new SqlDataAdapter(com);
dtb = new DataTable();
da.Fill(dtb);
if (dtb.Rows[0] != null)
{
BindData();
}
GridView1.AutoGenerateEditButton = true;
GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
// }
}
protected void BindData()
{
GridView1.DataSource = dtb;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = dtb;
GridView1.DataBind();
}
}
When a data source control that supports updating is bound to a GridView control, the GridView control can take advantage of the data source control's capabilities and provide automatic updating functionality.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogenerateeditbutton.aspx

Resources