How to download a file from a specific row in GridView - c#

I need some assistance with downloading a file in a specific row in my GridView.
This is my code for the the GridView markup:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="id"
CssClass="mydatagrid"
Width="550px"
BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None"
BorderWidth="1px"
CellPadding="3"
CellSpacing="2"
AllowSorting="true">
<Columns>
<asp:BoundField DataField="filename" HeaderText="Name" />
<asp:BoundField DataField="datestamp" HeaderText="Date" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
Text="Download"
ControlStyle-CssClass="btn btn-success"
CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" width="250px" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
And then for downloading the file I have:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["filecontent"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
So what happens now is when I click on the download it always download the first row's file instead of the row I clicked on to download.
I know I need to specify on which row I have clicked in order to download the file, but not sure on how to accomplish it?
Thanks

It is because of this line
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
You then need to change from onclick to a grid command:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server"Text="Download"
ControlStyle-CssClass="btn btn-success" CommandName="MyCommand" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
</ItemTemplate>
</asp:TemplateField>
And in your code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["id"];
// you can run your query here
}
}
In your case:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
var val = this.GridView1.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = val;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
You need to also add the onrowcommand="ContactsGridView_RowCommand" to your Gridview
<asp:GridView ID="GridView1" runat="server" onrowcommand="ContactsGridView_RowCommand"

Related

call oracle procedure using asp.net and edit gridview row from another page

I am stuck because when i update the edit page on button click event, my page navigates to the home page that contains the gridview but the gridview row is not updated and remains the same. And please advice me how i can edit a page on a button click event using session.
This is the manager aspx page:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" OnRowCommand="GridView1_RowCommand" >
<%-- <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" DataKeyNames="USERID" DataSourceID="SqlDataSource1">--%>
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="USERID" HeaderText="USERID" ReadOnly="True" SortExpression="USERID"/>
<asp:BoundField DataField="FIRSTNAME" HeaderText="FIRSTNAME" SortExpression="FIRSTNAME" />
<asp:BoundField DataField="LASTNAME" HeaderText="LASTNAME" SortExpression="LASTNAME" />
<asp:BoundField DataField="EMAIL" HeaderText="EMAIL" SortExpression="EMAIL" />
<asp:BoundField DataField="PASSWORD" HeaderText="PASSWORD" SortExpression="PASSWORD" />
<asp:TemplateField >
<ItemTemplate>
<%--<asp:LinkButton ID="LinkButton1" runat="server" CommandName="EditButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" >Edit</asp:LinkButton>--%>
<asp:Button ID="btnEdit" runat="server" Width="60" Text="Edit" CommandName="EditButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="DeleteButton" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%-- hiddenfield for session--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdid" Value='<%#Eval("USERID")%>' runat="server"></asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
Navigate to edit.aspx page on clicking of edit button:
namespace WebApplicationSystem
{
public partial class Edit : System.Web.UI.Page
{
int empno = 0;
protected void Page_Load(object sender, EventArgs e)
{
empno = Convert.ToInt32(Request.QueryString["USERID"].ToString());
if (!IsPostBack)
{
BindTextBoxvalues();
}
}
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
OracleConnection con = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand("select * from LOGIN where USERID=" + empno, con);
DataTable dt = new DataTable();
OracleDataAdapter Oda = new OracleDataAdapter(cmd);
Oda.Fill(dt);
txtid.Text = dt.Rows[0][0].ToString();
txtfname.Text = dt.Rows[0][1].ToString();
txtlname.Text = dt.Rows[0][2].ToString();
txtemail.Text = dt.Rows[0][3].ToString();
txtpassword.Text = dt.Rows[0][4].ToString();
}
protected void btnregistration_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
OracleConnection con = new OracleConnection(constr);
OracleCommand cmd = new OracleCommand("UPDATELOGIN", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
OracleParameter OP1 = cmd.Parameters.Add("USERID", OracleDbType.Varchar2);
OP1.Direction = ParameterDirection.Input;
OP1.Value = txtid;
OracleParameter OP2 = cmd.Parameters.Add("FIRSTNAME", OracleDbType.Varchar2);
OP2.Direction = ParameterDirection.Input;
OP2.Value = txtfname;
OracleParameter OP3 = cmd.Parameters.Add("LASTNAME", OracleDbType.Varchar2);
OP3.Direction = ParameterDirection.Input;
OP3.Value = txtlname;
OracleParameter OP4 = cmd.Parameters.Add("EMAIL", OracleDbType.Varchar2);
OP4.Direction = ParameterDirection.Input;
OP4.Value = txtemail;
OracleParameter OP5 = cmd.Parameters.Add("PASSWORD", OracleDbType.Varchar2);
OP5.Direction = ParameterDirection.Input;
OP5.Value = txtpassword;
cmd.ExecuteNonQuery();
OracleDataAdapter oda = new OracleDataAdapter(cmd);
//Fill the DataTable
oda.Fill(dt);
con.Close();
Response.Redirect("~/Manager.aspx");
}
}
}
To update your GridView after each click, don't forget to redefine your data source:
GridView1.DataSource = //your DataTable
GridView1.DataBind();
I'm not sure that I understand what you want to do with the session manager, but you can access the session object by HttpSessionState.Session.

ASP.net Image retrieved from database not show in Chrome and Firefox except IE and Edge

I have created a food ordering web page. I have saved the images in database as varbinary. It correctly displays on IE and Edge. But not in Firefox and Chrome. (I am seeing a torn page icon instead where the image should be).
I have write this code in the ImageLoad.aspx.cs
public partial class ImageLoad : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ImageID"] != null)
{
string strQuery = "select Name, contentType, Data, description from food where fid=#id";
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["RestaurantDBConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
}
catch
{
dt = null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
if (dt != null)
{
try
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["description"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
}
}
And included below code in the desserts.aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "False" Font-Names = "Arial" Caption = "Available Food" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black">
<Columns>
<asp:BoundField DataField = "fID" HeaderText = "Item ID" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Name" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:ImageField DataImageUrlField = "fID" DataImageUrlFormatString = "/ImageLoad.aspx?ImageID={0}" ControlStyle-Width = "200" ControlStyle-Height = "200" HeaderText = "Preview">
<ControlStyle Height="150px" Width="150px"></ControlStyle>
</asp:ImageField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" HorizontalAlign="Center"/>
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Here is the preview.. I have attached the preview below.
Image -for IE OK but Firefox cannot display that
Here is the db contents > DB content image
I don't know what it does .. but I have removed the second content-disposition named Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["description"].ToString());
Now Firefox shows the Images. Credit goes to #Mathew

ASP.NET: DataGridView not showing in website

I have a problem with my datagridview. It works when the code is being executed in local but when i hosted it in the web server, the problem occurs.
The .aspx code is.
<asp:GridView ID="gvDocu" runat="server" AlternatingRowStyle-BackColor="White"
AlternatingRowStyle-ForeColor="#000" AutoGenerateColumns="False"
BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px"
CellPadding="4" CellSpacing="2" ForeColor="Black"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" Width="250px">
<Columns>
<asp:BoundField DataField="DocumentName" HeaderText="File Name" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server"
CommandArgument='<%# Eval("C_ID") %>' OnClick="DownloadFile" Text="Download"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
The page load code is.
if (!this.IsPostBack)
{
BindGrid();
}
string uname = Session["ApplicantUsername"].ToString();
username.Text = uname;
It is binded in the code behind with this code.
private void BindGrid()
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT C_ID,DocumentName FROM CustomerRegistration WHERE ApplicantUsername = '" + username.Text + "'";
cmd.Connection = cs;
cs.Open();
gvDocu.DataSource = cmd.ExecuteReader();
gvDocu.DataBind();
cs.Close();
}
}
The downloading link code behind is.
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DocumentName,DocumentContent,DocumentExt FROM CustomerRegistration WHERE C_ID=#C_ID";
cmd.Parameters.AddWithValue("#C_ID", id);
cmd.Connection = cs;
cs.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["DocumentContent"];
contentType = sdr["DocumentExt"].ToString();
fileName = sdr["DocumentName"].ToString();
}
cs.Close();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I don't know the problem if it is in the web server or in my code. Thank you!

Approve / reject through dropdownlist

Previously I tried to approve / reject through button and try to code it..
This is code when I add buttons of approve / reject
protected void GrdFileApprove_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "_Approve")
{
//using (SqlConnection con = DataAccess.GetConnected())
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
Button Prove_Button = (Button)row.FindControl("BtnApprove");
SqlCommand cmd = new SqlCommand("approveee", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
//con.Execute("approve", new { UserID, DocID, ApproveID });
cmd.Parameters.Add(new SqlParameter("#UserID", UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Not Approve";
}
finally
{
con.Close();
}
}
}
else if (e.CommandName == "_Reject")
{
using (SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings
["mydms"].ConnectionString))
{
try
{
con.Open();
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)
((Control)e.CommandSource).NamingContainer;
LinkButton Prove_Button = (LinkButton)row.FindControl("Button1");
SqlCommand cmd = new SqlCommand("sprejectapprove", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#UserID",UserID));
cmd.Parameters.Add(new SqlParameter("#DocID", DocID));
cmd.Parameters.Add(new SqlParameter("#ApproveID", ApproveID));
int result = cmd.ExecuteNonQuery();
if (result != 0)
{
GrdFileApprove.DataBind();
}
}
catch
{
apfi.Text = "Rejct";
}
finally
{
con.Close();
}
}
}
}
and this grdiview when I add dropdown..
<asp:GridView ID="GrdFileApprove" runat="server" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal" AutoGenerateColumns="False"
onrowcommand="GrdFileApprove_RowCommand" OnRowDataBound="OnRowDataBound" >
<Columns>
<asp:TemplateField HeaderText="S no">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
<asp:HiddenField runat="server" ID="HdnFileID" Value='<%# Eval("DocID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocID" HeaderText="DocumentID" />
<asp:BoundField DataField="DocName" HeaderText="DocName" />
<asp:BoundField DataField="Uploadfile" HeaderText="File Name" />
<asp:BoundField DataField="DocType" HeaderText="Document" />
<asp:BoundField DataField="DepType" HeaderText="Department" />
<%-- <asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
--%> <asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="White" ForeColor="#333333" />
<FooterStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Now I want to code of dropdown.. when I click on approve/reject it can be approve/reject
how to code it and how to approve or reject through dropdown..
I have changed markup for DropDownList4:
<asp:DropDownList ID="DropDownList4" runat="server" class="vpb_dropdown" AutoPostBack="true" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged">
<asp:ListItem Text="Approve" Value="Approve"></asp:ListItem>
<asp:ListItem Text="Reject" Value="Reject"></asp:ListItem>
</asp:DropDownList>
And in the code:
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
if (ddl.SelectedValue == "Approved")
{
//Code to approve
}
else if (ddl.SelectedValue == "Reject")
{
//Code to reject
}
}

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