Storing BoundField Value in HiddenField on Button Click - c#

I'm having trouble with setting a HiddenField's value to a GridView item value. What I want to do is get the value of a BoundField (in this case, "FIPSCountyCode") in a GridView and store it in a HiddenField when the user clicks a button (in this case, "btnEdit") to make changes to a entry in the grid. I haven't used HiddenFields before, so I have forgotten what to do here.
The HiddenField is setup like this:
<asp:HiddenField ID="hdnFIPS" Value='<%#Eval("FIPSCountyCode")%>' runat="server" />
This is what the GridView is setup like:
<asp:GridView ID="CountyList" runat="server" AutoGenerateColumns="False" Width="90%" SkinId="PagedList" PagerSettings-Position="TopAndBottom" PagerStyle-Wrap="True">
<Columns>
<asp:BoundField HeaderText="County Code" DataField="FIPSCountyCode" />
<asp:BoundField HeaderText="State Code" DataField="StateCode" />
<asp:BoundField HeaderText="County Name" DataField="CountyName" />
<asp:BoundField HeaderText="Tax Rate" DataField="TaxRate" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" SkinID="EditIcon" OnClick="EditInfo" CommandName="DoEdit" />
<asp:ImageButton ID="DeleteButton" runat="server" SkinID="DeleteIcon" CommandName="DoDelete"
OnClientClick="return confirm('Are you sure you want to remove this item and all of its options?')"
CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle CssClass="even" />
</asp:GridView>
And this is the code behind:
public partial class Admin_County_Info : CommerceBuilder.UI.AbleCommerceAdminPage
{
private string redirectString = String.Empty;
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
PopulateCountyGrid();
}
protected void PopulateCountyGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT [FIPSCountyCode], [StateCode], [CountyName], [TaxRate] FROM [baird_InfoCounty]", cn);
cmd.CommandType = CommandType.Text;
cn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
CountyList.DataSource = dr;
CountyList.DataBind();
}
}
catch (Exception eX)
{
}
}
#region Clicks and Event Handlers
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}
protected void AddInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("~/Admin/Taxes/AddEditCountyInfo.aspx");
}
}
}
This must be a really dumb question but I'm really not sure how to proceed. Any help would be great!

You can get the value of FIPSCountyCode from the BoundField this way:
protected void EditInfo(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
GridViewRow gvr = ((ImageButton)sender).NamingContainer as GridViewRow;
hdnFIPS.Value = gvr.Cells[0].Text;
redirectString = "~/Admin/Taxes/AddEditCountyInfo.aspx?FIPSCountyCode=" + hdnFIPS.Value;
Response.Redirect(redirectString);
}
}

Related

ASP.NET c# Gridview OnRowUpdating not working

I'm working in Visual Studio 2015.
When the Gridview loads, I can click on "Edit".
When I click Cancel I'm just getting back to the Gridview.
So that good, but if I click "Update" he is doing the same thing as what is happening at "Cancel". No errors.
Here is the method for the OnRowUpdating :
protected void UpdateHandleiding(object sender, GridViewUpdateEventArgs e)
{
SqlConnection Sqlconnection1 = new SqlConnection();
Sqlconnection1.ConnectionString = (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblID")).Text;
//string Naam = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtNaam")).Text;
//string URL = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtURL")).Text;
GridViewRow row = GridView1.Rows[e.RowIndex];
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Naam = (row.Cells[1].Controls[0] as TextBox).Text;
string URL = (row.Cells[2].Controls[0] as TextBox).Text;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Handleidingen SET Naam=#Naam, URL=#URL WHERE ID=#ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#Naam", Naam);
cmd.Parameters.AddWithValue("#URL", URL);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
}
Here is my OnRowEditing & OnRowCancelingEdit which do work :
protected void EditHandleiding(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
ShowHandleidingen();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
ShowHandleidingen();
}
Here is my Gridview :
<asp:GridView ID="GridView1" runat="server" CssClass="grid-center" AutoGenerateColumns="False"
DataKeyNames="ID" EnableModelValidation="True" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="EditHandleiding" OnRowUpdating="UpdateHandleiding" OnRowCancelingEdit="CancelEdit">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Naam" HeaderText="Naam"/>
<asp:BoundField DataField="URL" HeaderText="URL"/>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
this is simple situation caused by the post back events in asp.net, in the Update Method the page is reloaded from the begining, even if you give new values to the data that you want too submit in the database, asp.net will take the one in the page_load method, when you fill the database in the first place at the page_load method add this condition :
private void Page_Load()
{
if (!IsPostBack)
{
// Fill up the gridView with the data that you want
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
}
replace object sender, GridViewUpdateEventArgs e
to
object sender, GridViewRowEventArgs e
Simply change gridview in aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
and then put
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{}

selecting the row in gridview using row index

protected void select_click(object sender, GridViewCommandEventArgs e)
{
try
{
DBLibrary db = new DBLibrary();
int index = Convert.ToInt32(e.CommandArgument);
* string FeeId = gridv1.Rows[index].Cells[1].Text;*
if (e.CommandName == "Select")
{
string str = "SELECT AnuFeeMaster.FeeId ,AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.FeeId ='" + FeeId + "')";
SqlDataReader dr = db.ExecuteReader(str);
while (dr.Read())
{
Session["name"] = dr["sname"].ToString();
Session["id"] = dr["StudentId"].ToString();
Session["mth"] = dr["Month"].ToString();
Session["yr"] = dr["Year"].ToString();
Session["tot"] = dr["FeeAmount"].ToString();
}
}
}
catch { }
}
Above is my code what i used to access that i am not getting the value r data from dat Please suggest me, * mark which i used that show where i am getting the error
create proper grid rowcommand Event
aspx code
<asp:GridView ID="Gv" runat="server" AllowPaging="true" OnRowCommand="Gv_RowCommand" PageSize="10" EmptyDataText="No Records Found !">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="20%">
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandArgument='<%#Eval("Demo_Code") %>' CommandName="select" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Coulmn1" HeaderText="Coulmn2" />
<asp:BoundField DataField="Coulmn2" HeaderText="Coulmn2" />
</Columns>
</asp:GridView>
aspx.cs Code
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
}
}
You should properly use RowCommand event of gridview.
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
You can catch the button click event like below:
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

ImageButton Not getting the GridView cell value

The code was working before and all i did was add a new textbox in the header template of the gridview.
So What is my code doing:
i have an image button on my gridview view when clicked i take the value of of the current row of the gridview and the value of cell 3 and set it equal to my textbox. Then based on that value i am making two details view visible using a modal popup extender, one detail view renders correctly but will not function unless it gets the value from textbox10.text as a parameter, another details view will not even show the details because the select query takes the textbox10.text as a parameter.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (!IsPostBack)
{
}
else
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1 = (GridViewRow)imgbtn.NamingContainer;
string workordernum = GridView1.Cells[3].Text;
TextBox10.Text = workordernum;
//TextBox10.Text = "1";
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}
}
when i put the above code in debug mode:
after debug completed:
When i set the textbox10.text = 1 and ran the application:
complete application with value 1:
.aspx code of the details view:
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="pnl2" PopupControlID="pnl2" BackgroundCssClass="modalBackground" DropShadow="False" X="30" Y="300" ValidateRequestMode="Inherit"></asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField2" runat="server" />
<asp:Panel ID="pnl2" runat="server" Width="881px" Height="175px" CssClass="pnl2BackGround" >
<asp:DetailsView ID="DetailsView2" runat="server" DataSourceID="SqlDataSource3" BackColor="#593B03" Height="175px" Width="881px" Font-Bold="True" ForeColor="White" PostBack = "False" AutoGenerateRows="False" DataKeyNames="WorkOrderNum" >
<Fields>
<asp:BoundField DataField="WorkOrderNum" HeaderText="WorkOrderNum" InsertVisible="False" ReadOnly="True" SortExpression="WorkOrderNum" />
<asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
<asp:BoundField DataField="CompletionDate" HeaderText="CompletionDate" SortExpression="CompletionDate" DataFormatString="{0:dd-M-yyyy}" />
<asp:BoundField DataField="MachineDescription" HeaderText="MachineDescription" SortExpression="MachineDescription" />
<asp:BoundField DataField="MachineLocation" HeaderText="MachineLocation" SortExpression="MachineLocation" />
<asp:BoundField DataField="Type_of_Work_Order" HeaderText="Type_of_Work_Order" SortExpression="Type_of_Work_Order" />
<asp:BoundField DataField="Work_Required" HeaderText="Work_Required" SortExpression="Work_Required" />
</Fields>
</asp:DetailsView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:WorkOrderConnectionString6 %>" SelectCommand="SELECT [WorkOrderNum], [Requestor], [Date], [Department], [CompletionDate], [MachineDescription], [MachineLocation], [Type of Work Order] AS Type_of_Work_Order, [Work Required] AS Work_Required FROM [Master] WHERE ([WorkOrderNum] = #WorkOrderNum)">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox10" Name="WorkOrderNum" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
The Code i am using for the searching of the gridview from the header template:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Filter"] = "All";
DetailsView1.Visible = false;
TextBox10.Visible = false;
DetailsView2.Visible = false;
DetailsView3.Visible = false;
ReportViewer1.Visible = false;
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
String WorkOrderConnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["WorkOrderConnectionString3"].ConnectionString;
SqlConnection con = new SqlConnection(WorkOrderConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("spx_GetWorkOrderNum");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Filter", ViewState["Filter"].ToString());
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
TextBox TextBox92 = (TextBox)GridView1.HeaderRow.FindControl("WorkOrderNum");
}
protected void TextBox92_TextChanged(object sender, EventArgs e)
{
TextBox TextBox92 = (TextBox)sender;
ViewState["Filter"] = TextBox92.Text;
this.BindGrid();
}
I am suspecting that post back might be the issue, some where in the code it is doing an unnessary post back so when i click the imagebutton it is not getting the value
Please help me find the error in my code as the debugger is not helping me and plus this was a working code before :(
WHY THE TEXTBOX VALUE = "" INSTEAD OF THE GRIDVIEW CELL VALUE??????
Thanks
Since Gridview is a Control and TextBox is also an Control within the Gridview control we nee to do this:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton imgbtn = (ImageButton)sender;
GridViewRow GridView1Row = (GridViewRow)imgbtn.NamingContainer;
Label FLabel = GridView1Row.Cells[2].Controls[0].FindControl("Label1") as Label;
string workordernum = FLabel.Text;// GridView1Row.Cells[3].Text;
TextBox10.Text = workordernum;
ModalPopupExtender2.Show();
DetailsView2.Visible = true;
ModalPopupExtender1.Show();
DetailsView1.Visible = true;
}

Javascript confirmation Box not appear on delete in gridview

When click on delete link-button in gridview, Confirmation Box not appeared. I write this code but I don't know why it's not working...
<asp:GridView ID="gvwAuctionExport" runat="server" AutoGenerateColumns="false" OnRowCommand="gvwAuctionExport_RowCommand" OnRowDataBound="gvwAuctionExport_RowDataBound" OnRowDeleting="gvwAuctionExport_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="btn-group btn-group-xs" id="bgroup">
<asp:LinkButton ID="lnkInspectionDelete" runat="server" Text="Delete" CssClass="btn btn-danger" CommandArgument='<%# Eval("inspection_id") %>' CommandName="Delete"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="address" HeaderText="Address" />
<asp:BoundField DataField="city" HeaderText="City" />
<asp:BoundField DataField="state" HeaderText="State" />
</Columns>
</asp:GridView>
protected void gvwAuctionExport_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int InspectionID = Convert.ToInt32(e.CommandArgument);
string status = string.Empty;
status = DACls.DeleteInspectionByID(InspectionID);
}
}
protected void gvwAuctionExport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton l = (LinkButton)e.Row.FindControl("lnkInspectionDelete");
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record");
}
}
protected void gvwAuctionExport_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bindGridView();
}
public void bindGridView(){
DataSet DS = new DataSet();
SqlConnection DBCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
SqlCommand Cmd = new SqlCommand("USP_Inspection_Export", DBCon);
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter AHadp = new SqlDataAdapter(Cmd);
AHadp.Fill(this.DS);
DataTable dt = DS.Tables[0];
this.gvwAuctionExport.DataSource = dt;
this.gvwAuctionExport.DataBind();
}
When I click on delete button and check from debugger it is not going to GridView RowDataBound function scope. I don't know what happening here?

Gridview popout window to edit when clicked on a column

I have a gridview. I need to include a hyperlink to one of the columns so when the user clicks the link a popout should come with option to Edit and save. After the save the gridview should automatically get refreshed.
Following is my Gridview Code:
<asp:GridView ID="EmployeeGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="Emp_id" onrowcancelingedit="EmployeeGridView_RowCancelingEdit"
onrowediting="EmployeeGridView_RowEditing" onrowdeleting="EmployeeGridView_RowDeleting"
onrowupdating="EmployeeGridView_RowUpdating" Width="395px"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="EmployeeGridView_RowDataBound" AllowPaging="True"
onpageindexchanging="EmployeeGridView_PageIndexChanging1" PageSize="5">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText = "Action">
<ItemTemplate>
<asp:CheckBox ID = "chkDelete" runat = "server" AutoPostBack="True"
oncheckedchanged="chkDelete_CheckedChanged" />
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sr.No">
<ItemTemplate>
<asp:Label ID = "lblID" runat = "server" Text = '<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID = "lblEmpName" runat = "server" Text = '<%# Eval("Emp_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempname" runat="server" Text='<%#Eval("Emp_name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experience">
<ItemTemplate>
<asp:Label ID = "lblEmpExp" runat = "server" Text = '<%# Eval("Emp_exp") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempexp" runat="server" Text='<%#Eval("Emp_exp") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID = "lblEmpAddress" runat = "server" Text = '<%# Eval("Emp_address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempaddress" runat="server" Text='<%#Eval("Emp_address") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" ButtonType ="Button"
HeaderText="Edit" ControlStyle-BackColor= "#15524A" >
<ControlStyle BackColor="#15524A"></ControlStyle>
</asp:CommandField>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" HeaderText="Delete" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
The code behind is :
public partial class _Default : System.Web.UI.Page
{
SqlConnection connstr = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
Session["sortBy"] = e.SortExpression;
FillGrid();
}
protected void Page_Load(object sender, EventArgs e)
{
Session["sortBy"] = null;
if (!Page.IsPostBack)
{
FillGrid();
BindGrid();
}
}
public void FillGrid()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("GetEmployeeInfo", con);
SqlDataReader dr = cmd.ExecuteReader();//it reads froword only data from database
DataTable dt = new DataTable();//object of data table that uses to conatin whole data
dt.Load(dr);//Sql Data reader data load in data table it is DataTable Method.
EmployeeGridView.DataSource = dt;
EmployeeGridView.DataBind();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
protected void EmployeeGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EmployeeGridView.EditIndex = -1;
FillGrid();
}
protected void EmployeeGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
EmployeeGridView.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void EmployeeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());//Get Each Row unique value from DataKeyNames
string name = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempname")).Text;//get TextBox Value in EditItemTemplet that row is clicked
string experience = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempexp")).Text;
string address = ((TextBox)EmployeeGridView.Rows[e.RowIndex].FindControl("txtempaddress")).Text;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("EmployeeUpdate", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.Parameters.AddWithValue("#emp_name ", name);
cmd.Parameters.AddWithValue("#emp_exp ", experience);
cmd.Parameters.AddWithValue("#emp_address ", address);
cmd.ExecuteNonQuery();//Sql Command Class method return effected rows use for insert,update, delete
EmployeeGridView.EditIndex = -1;// no row in edit mode
FillGrid();
}
protected void EmployeeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empid = Convert.ToInt32(EmployeeGridView.DataKeys[e.RowIndex].Value.ToString());
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#emp_id ", empid);
cmd.ExecuteNonQuery();
FillGrid();
}
protected void EmployeeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
EmployeeGridView.PageIndex = e.NewPageIndex;
FillGrid();
}
protected void buttonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
var lblID = row.FindControl("lblID") as Label;
Response.Write(lblID.Text + "<br>");
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand("Delete from tbl_employee where Emp_id=#emp_id", conn);
// comm.CommandType = CommandType.StoredProcedure;
conn.Open();
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.ExecuteNonQuery();
conn.Close();
}
}
FillGrid();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in EmployeeGridView.Rows)
{
var chk = row.FindControl("chkDelete") as CheckBox;
if (chk.Checked)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
var lblID = row.FindControl("lblID") as Label;
var lblEmpName = row.FindControl("lblEmpName") as Label;
var lblEmpExp = row.FindControl("lblEmpExp") as Label;
var lblEmpAddress = row.FindControl("lblEmpAddress") as Label;
//Response.Write(lblFirstName.Text + "<br>");
SqlCommand comm = new SqlCommand("EmployeeUpdate", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("#emp_id", int.Parse(lblID.Text));
comm.Parameters.AddWithValue("#emp_name", EmpName.Text);
comm.Parameters.AddWithValue("#emp_exp", EmpExp.Text);
comm.Parameters.AddWithValue("#Emp_address", EmpAddress.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
EmpName.Visible = false;
EmpExp.Visible = false;
EmpAddress.Visible = false;
}
}
FillGrid();
}
}
For the column Name I need to make a hyperlink and when clicked the popout should come to edit and view data
Not sure I fully understand what do you need but you can check out how modal popup works in MS AJAX toolkit and try to emulate sample code that comes with the download.

Categories

Resources