Here is my aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True" EnablePersistedSelection="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is code behind:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
GridViewRow gr = GridView1.SelectedRow;
gr.Cells[1].Text = Textusername.Text;
gr.Cells[2].Text = Textclass.Text;
gr.Cells[3].Text = Textsection.Text;
gr.Cells[4].Text = Textaddress.Text;
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
The selected row did not select in gridview. May i know how to enable gridview row. I used msdn and other documents and i followed,but nothing helps.
I design i set enable selection, but still i didn't find out issue.
Can anyone help me?
Thanks,
Basically we get SelectedRow of GridView Upon some GridviewRow Action event like OnSelectedIndexChanged , OnSelectedIndexChanging , OnRowEditing or from Template control like Button click. But here in your coding I don't think your btnsub_Click is inside Gridview so If you want to use the SelectedGridViewRow after your GridviewRow Action event then save the index in some temporary variable or pass the variable to method as argument.
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = Gridview1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
OR In OnRowEditing also you can get the index of row
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hidval.Value = index.ToString();
}
}
and on button Click you can get the hiddenfield value as index:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
if(!String.IsNullOrEmpty(hiddenfield.Value))
{
int index = Convert.ToInt16(hiddenfield.Value);
GridView1.Rows[index].Cells[1].Text = Textusername.Text;
GridView1.Rows[index].Cells[2].Text = Textclass.Text;
GridView1.Rows[index].Cells[3].Text = Textsection.Text;
GridView1.Rows[index].Cells[4].Text = Textaddress.Text;
}
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
Related
I created a grid view that contains a column for images, after I write all necessary code the image is still not showing. Can you look at the code and see if there is something that i'm doing wrong? This is my ASP.NET Grid View:
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Height="229px" Width="404px">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<img id="img1" src='Handler1.ashx.cs?ProductID=<%# Eval("ProductID").ToString() %>' height="70" width="70"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ProductID") %>' OnClick="lnk_OnClick">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my button that when clicked should display the images in the ASP.NET grid view
protected void btnSave_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("ProductCreateOrUpdate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#ProductID", (hfProductID.Value == "" ? 0 : Convert.ToInt32(hfProductID.Value)));
sqlCmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Image", FileUpload2.FileBytes);
sqlCmd.Parameters.AddWithValue("#Description", txtDescription.Text.Trim());
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
string productID = hfProductID.Value;
Clear();
if (productID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
FillGridView();
}
And this is the general Handler.ashx
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string Constr = System.Configuration.ConfigurationManager.ConnectionStrings[#"connection String"].ToString();
string pici = context.Request.QueryString["ProductID"];
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(Constr))
{
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT Image FROM Product WHERE ProductID=#ProductID", conn))
{
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("ProductID", pici));
conn.Open();
using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Image")]);
reader.Close();
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I am using radio button inside gridivew. I want to select 1 radio button at a time not multiple. I tried this but not working i.e it disables the only selected one too.
protected void btnAward_CheckedChanged(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in gvAppliedWorks.Rows)
{
int RowIndex = gr.RowIndex;
int AppliedWorkID = gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
RadioButton rdbtn = gr.FindControl("btnAward") as RadioButton;
if (rdbtn.Checked == true)
{
//if(RowIndex )
rdbtn.Checked = false;
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
}
Try this code:
GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" id="rbtn1" name="rbtn" GroupName="rgrp" onclick = "RadioCheck(this);" ></asp:RadioButton>
<asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code for filling gridview from DB
protected void bind()
{
using (SqlConnection con = new SqlConnection("Connection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tableName", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
Finally add this script to avoid multiple selection
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
I'm using gridview with edit and delete button.
When i delete particular row in gridview, it will be removed. but again i reload the page, the deleted row again displayed. I mean, row is not remove in database.
Here is my code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hiddenfield.Value = index.ToString();
Textid.Text = gr.Cells[1].Text;
Textusername.Text = gr.Cells[2].Text;
Textclass.Text = gr.Cells[3].Text;
Textsection.Text = gr.Cells[4].Text;
Textaddress.Text = gr.Cells[5].Text;
}
else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
and asps file:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True"
EnablePersistedSelection="True" BackColor="White" EnableViewState="true" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
<ControlStyle BorderColor="#CCFF66" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle BackColor="#FF66FF" />
</asp:GridView>
storedprocedure:
ALTER PROCEDURE StoredProcedure4
(
#id int
)
AS
begin
Delete from Student where id=#id
End
I'm new to .net. can anyone help me to fix this?
Thanks,
Alternative way could be,
Short answer
Pass ID using commandargument
Full answer
Replace
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
By
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Eval("ID") %>' CommandName="Deleterow"></asp:Button>
in aspx and in cs
Replace
else if (e.CommandName == "Deleterow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", gr.Cells[0].Text);
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
By
else if (e.CommandName == "Deleterow")
{
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#ID", Convert.ToInt32(e.CommandArgument));
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
pass parameter not valid #id change #ID
ALTER PROCEDURE StoredProcedure4
(
#ID as int=0
)
AS
begin
Delete from Student where id=#ID
End
Pass Id as command argument in delete button and access on code behind like below.
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
else if (e.CommandName == "Deleterow")
{
SqlCommand com = new SqlCommand("StoredProcedure4", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Convert.ToInt32(e.CommandArgument));
var id = Int32.Parse(e.CommandArgument.ToString());
GridView1.Rows[id].Visible = false;
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
here i want to have no.of coloumns i have checked and deleted in lable
i have used following code to execute my query of deleting multiple values in gridview using checkbox
here is my code and script part
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
grd_bnd();
}
}
private void grd_bnd()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from student", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
}
}
grd_bnd();
}
}
and here is script
<asp:GridView ID="GridView1" runat="server" DataKeyNames="rollno" AllowSorting="true" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkboxdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat ="server" Text='<%#Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roll No.">
<ItemTemplate>
<asp:Label ID="lblrollno" runat ="server" Text='<%#Eval("rollno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<ItemTemplate>
<asp:Label ID="lblbatch" runat ="server" Text='<%#Eval("batch") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblcourse" runat ="server" Text='<%#Eval("course") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
<asp:Button ID="Button3" runat="server" Font-Bold="True" Text="Delete Selected" ForeColor="#000066" OnClick="Button3_Click" />
<asp:Label ID="Label1" runat="server" ForeColor="#666666"></asp:Label>
i wanna get the number of entities deleted in above lable , lable1.
Simply add a count before your loop
protected void Button3_Click(object sender, EventArgs e)
{
int rows = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox1 = (CheckBox)row.FindControl("checkboxdelete");
if (checkbox1.Checked)
{
int rollno = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
//CheckBox checkbox1 = (CheckBox)row.FindControl("checkbox1");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
SqlCommand cmd = new SqlCommand("delete from student where rollno = #rollno ", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#rollno", SqlDbType.Int).Value = rollno.ToString();
con.Open();
rows += cmd.ExecuteNonQuery(); //Can return 0 if no rows were deleted!
con.Close();
cmd.Dispose();
}
}
grd_bnd();
MessageBox.Show(String.Format("Rows affected {0}", rows);
}
You can use the return value of ExecuteNonQuery:
int numDeleted = cmd.ExecuteNonQuery();
MSDN: returns the number of rows affected.
If you want the total rows use a variable:
int totalNumDeleted = 0;
foreach (GridViewRow row in GridView1.Rows)
{
// ...
int numDeleted = cmd.ExecuteNonQuery();
totalNumDeleted += numDeleted;
}
Label1.Text = string.Format("{0} students were deleted successfully.", totalNumDeleted);
this is my code ..while editing and deleting row index always taking zero on-wards...delete command not at all working....if i try to edit anything only 2nd row onwards its working...delete command not at all working..i think it is because of row index..please any one help me thanks in advance....
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
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;
public partial class Manager_Payments : System.Web.UI.Page
{
//SqlConnection con =new SqlConnection("Data Source=sqlexpress;Initial Catalog=isoqrmssys;User ID=sa;password=123456;Integrated Security=True");
Business BL = new Business();
//protected Int64 stf_ID, vmember;
//protected DateTime SRDT;
private System.Drawing.Color a;
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
loadgridview();
}
private void loadgridview()
{
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select * from CustomerProfMain", con);
//string sql = "SELECT * FROM CustomerProfMain";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
//return ds.Tables[0];
Grd_View.DataSource = ds.Tables[0];
Grd_View.DataBind();
con.Close();
}
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//string RowIndex = int.Parse(e.CommandArgument.ToString());
// Session["rowid"] = RowIndex;
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Select * from CustomerProfMain where CustomerCode='" + e.CommandArgument.ToString() + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt=ds.Tables[0];
TextBox1.Text = dt.Rows[0]["CustomerName"].ToString();
TextBox2.Text=dt.Rows[0]["Address"].ToString();
TextBox3.Text=dt.Rows[0]["TellNo"].ToString();
TextBox4.Text=dt.Rows[0]["FaxNo"].ToString();
TextBox5.Text=dt.Rows[0]["Email"].ToString();
Button1.Text = "Update";
}
if (e.CommandName == "Delete")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());
Session["rowid"] = RowIndex;
// DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Delete from CustomerProfMain where CustomerCode='" + RowIndex + "' ", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
protected void Grd_View_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Grd_View_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void Grd_View_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Button1.Text == "Add")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "insert into CustomerProfMain(CustomerName,Address,TellNo,FaxNo,Email) values('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "','" + TextBox4.Text.Trim() + "','" + TextBox5.Text.Trim() + "') ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
if (Button1.Text == "Update")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "update CustomerProfMain set CustomerName='" + TextBox1.Text.Trim() + "',Address='" + TextBox2.Text.Trim() + "',TellNo='" + TextBox3.Text.Trim() + "',FaxNo='" + TextBox4.Text.Trim() + "',Email='" + TextBox5.Text.Trim() + "' where CustomerCode='" + Session["rowid"] + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
}
}
"<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" cellpadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:BoundField DataField="FaxNo" HeaderText="FaxNo" SortExpression="FaxNo" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:CommandField ShowEditButton="true" SelectText="Edit" />
<asp:CommandField ShowDeleteButton="true" SelectText="Delete" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
"
Replace your grid view with this code
<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" CellPadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Edit" Text="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Delete" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
You didn't set CommandArgument here we set it as CommandArgument='<%#Eval("CustomerCode")%>' to your edit button and delete button
Try doing the following...on page load bind the grid ONLY if it's not a postback...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
loadgridview();
}
Then re-bind the grid at the end of the command event handler, I'll remove some data access logic for clarity...
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//...
loadgridview();
}
if (e.CommandName == "Delete")
{
//...
loadgridview();
}
}
Try this and Set GridView's AutoPostback property to true
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
loadgridview();
}
}