How to refresh Gridview after pressed a button in asp.net - asp.net

I am trying to make a simple library database. I list the search results in a gridview, then i have a textbox and a button, user enters the isbn and clicks loan button. Then, if there is enough number of items (itemNumber>0) it is loaned by user. Here is the screenshot of user interface:
My question is, when user clicks loan button the loan may or may not be succesful. In both cases, i print a message indicating whether loan is succesful or not, and i also want the updated gridview to be displayed. The problem is, after pressing the loan button the gridview disappears and i just see the textbox, button and the message on the screen. How can i show the updated version of gridview after pressing loan button?
Here is the code file:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchResults.aspx.cs" Inherits="Pages_SearchResults" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ISBN" DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ISBN" HeaderText="ISBN" ReadOnly="True"
SortExpression="ISBN" />
<asp:BoundField DataField="AuthorName" HeaderText="AuthorName"
SortExpression="AuthorName" />
<asp:BoundField DataField="AuthorlName" HeaderText="AuthorlName"
SortExpression="AuthorlName" />
<asp:BoundField DataField="ItemType" HeaderText="ItemType"
SortExpression="ItemType" />
<asp:BoundField DataField="PublishYear" HeaderText="PublishYear"
SortExpression="PublishYear" />
<asp:BoundField DataField="numOfCopies" HeaderText="Number of Copies"
SortExpression="numOfCopies" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Items] WHERE ([Title] LIKE '%' + #Title + '%')">
<SelectParameters>
<asp:FormParameter FormField="tSearchBox" Name="Title" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server" Text="Type ISBN to loan:"></asp:Label>
And here is the .cs file:
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;
public partial class Pages_SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
Int32 verify;
string title = GridView1.HeaderRow.Cells[0].Text, isbn = GridView1.HeaderRow.Cells[1].Text, name = GridView1.HeaderRow.Cells[2].Text, lname = GridView1.HeaderRow.Cells[3].Text, type = GridView1.HeaderRow.Cells[4].Text, year = GridView1.HeaderRow.Cells[5].Text;
}
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
string numQuery = "select numOfCopies from Items where ISBN='" + tLoanBox.Text + "'";
SqlCommand cmdnumQuery = new SqlCommand(numQuery, con);
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
int num=Convert.ToInt32(cmdnumQuery.ExecuteScalar());
result = cmd2.ExecuteNonQuery();
if (num > 0)
{
if (result > 0)
Response.Redirect("LoanSuccesfull.aspx");
}
else
notAvailable.Visible = true;
con.Close();
}
}
And here is the code for loan button:
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
result = cmd2.ExecuteNonQuery();
if (result > 0)
{
loanSuccesful.Visible = true;
Response.Redirect("LoanSuccesfull.aspx");
}
con.Close();
}
I appreciate any help. Thanks

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards

I was totally lost on why my Gridview.Databind() would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.

Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes is my GridView ID.

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.
Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
GridView1.DataBind()
End Sub

Related

how to calculate total price in gridview in ASP.NET

I have a gridview in ASP.NET,In that gridview there is one column of total price.I want to show to total price of all rows below the gridview and also if i will update or delete any row then it should update that total computed price.
Can anyone please help in this.
Thanks in advance.
The HTML Markup consists of an ASP.Net GridView. The ShowFooter property is set to true so that the GridView’s Footer Row is displayed.
Paging has been enabled for the GridView and OnPageIndexChanging event handler has been assigned.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" ShowFooter="true">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="Order ID" ItemStyle-Width="60" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" ItemStyle-Width="210" />
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-Width="60" DataFormatString="{0:N2}"
ItemStyle-HorizontalAlign="Right" />
</Columns>
</asp:GridView>
code behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT TOP 30 OrderID,";
query += "(SELECT ProductName FROM Products WHERE ProductID = details.ProductId) ProductName,";
query += "(Quantity * UnitPrice) Price";
query += " FROM [Order Details] details";
query += " ORDER BY OrderID";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
//Calculate Sum and display in Footer Row
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>("Price"));
GridView1.FooterRow.Cells[1].Text = "Total";
GridView1.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Cells[2].Text = total.ToString("N2");
}
}
}
}
}

Not able to access the ID while deleting the row from GridView

I am using a Gridview containing an ID. I want to write a Row_deleting event in which I access the ID from my .aspx page, but I am not getting it.
How can I do that?
Here is my Gridview Code
<asp:LinkButton ID="lnkDelete"
runat="server" CssClass="gridLink"
CommandArgument='<%# Eval("Serial_key") %>'
CommandName="Delete">
<b>Delete</b>
</asp:LinkButton>
first in your gridview set AutoGenerateDeletebutton=true then use this link
How to use the GridView AutoGenerateDeletebutton
protected void DeleteRowButton_Click(Object sender, GridViewDeleteEventArgs e)
{
var PN = GridView1.DataKeys[e.RowIndex].Values["Part_Number"];// this is how you get the right row to delete e.rowindex is used to do this
string PN = pn.ToString;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
con.Open();
string str = "DELETE * FROM XML WHERE ([Part_Numbber] = " + PN + ")";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Button1_Click(sender, e);
con.Close();
}
For Deleting any record from your database you need unique or Primary key column. If you want to delete record using column "Serial_key" . Then put the following code to Delete.
<ItemTemplate>
<asp:Label ID="lblSerial_key" runat="server" Text='<%# Eval("Serial_key") %>'></asp:Label>
<asp:Button ID="deleteButton" runat="server" CommandName="Delete" Text="Delete" /></ItemTemplate>
Now you can use the lblSerial_key to delete a row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Serial_key = string.Empty;
Label lblId = (Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblSerial_key");
Serial_key = lblId.Text.ToString();
string selectSQL = "delete from tablename where id='" + Serial_key + "'";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
// Create the command object
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL , con);
cmd.ExecuteNonQuery();
con.Close();
}

How to show image in GridView form database linq

i have a table with field named PIMAGE And i can't show this field.
gridview named:dgw-
my problem is that the gridview do not show the image
my code:
protected void Page_Load(object sender, EventArgs e)
{
StorDataContext stor = new StorDataContext();
var res = (from r in stor.Products
where r.PID!=13
select new {
name=r.PName,date=System.DateTime.Now.ToString(),company=r.Company,price=r.Price,quantity=r.Quantity,color=r.Color,size=r.Size,weight=r.PWeight,
PImage = r.PID});
GridView1.Visible = true;
GridView1.DataSource = res.ToList();
GridView1.DataBind();
}
and may ashx
public class ShowImg : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
Int32 pid;
if (context.Request.QueryString["getID"] != null)
{
pid = Convert.ToInt32(context.Request.QueryString["getID"]);
context.Response.ContentType = "image/jpeg";
Stream strm = GetImage(pid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
}
public Stream GetImage(int pid)
{
StorDataContext stor = new StorDataContext();
System.Data.Linq.Binary b = null;
byte[] ibyte = null;
Product product1 = stor.Products.First(p => p.PID == pid);
b = product1.PImage;
ibyte = b.ToArray();
return new MemoryStream((byte[])ibyte);
}
and aspx
<asp:TemplateField HeaderText="PImage">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/ShowImg.ashx?id=" + Eval("PImage") %>' />
</ItemTemplate>
</asp:TemplateField>
what's wrong?
use asp.net - sql server - linq
I'm assuming you mean you have an image field in the database.
There's lots of examples available on the net for this, here's one from the asp.net forums
The short version is, you would set the control
within the gridview to display the image. On the ImageField, you
would use the DataImageUrlField attribute to reference the name of the
field in the database that contains the binary image data. Also on
the ImageField, use the DataImageUrlFormatString to define a path
that, for example, points to an ASPX handler page and passes to it the
specific ID value from the DataImageUrlField.
The relevant line of code might look like this:
<asp:ImageField DataImageUrlField="MyImageID"
DataImageUrlFormatString="MyHandlerPage.aspx?theImageID={0}" /> A
complete example that uses this approach and shows you the code for
the handler page is at:
http://www.highoncoding.com/Articles/207_Displaying_Images_from_Database_in_GridView.aspx
or check out this one
public void ProcessRequest (HttpContext context) {
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select [Content] from Images where ID =#ID";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlParameter ImageID = new SqlParameter("#ID", SqlDbType.BigInt);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Content"]);
dReader.Close();
conn.Close();
}
and the aspx code
<asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="200px" Height="200px"
ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your page_load in aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
ad.Fill(dt);
}
GVImages.DataSource = dt;
GVImages.DataBind();
}
}
and finally your web.config
<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
<!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
...................
...................

how to check the duplicate filename in asp:fileupload?

i have an updatepanel and inside of it the contenttemplate is an asp:FileUpload..now when i will try to choose the file i want to check the filename in the database..i know my database part but how will i call the function in the server like for asp:TextBox i can use OnTextChanged something like that..but for asp:FileUpload is there anything by which i can check the filename and without clicking the button add?? my code
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" AutoPostBack="true" OnLoad="filename_Changed" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
my aspx.cs code
protected void filename_Changed(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string tuname = tutorialupload.PostedFile.FileName;
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
if (grpIDreader.HasRows)
{
f1.Text = "Duplicate filename.Sorry.";
}
else
{
f1.Text = "";
}
objsqlconn.Close();
}
now when i will choose the file..i want to call this function filename_Changed() and it will give me the result whether the filename is present or not..so i want to do it without clicking my the add button??
You should use the has file property, when true do you DB check, something like this
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
// Before attempting to save the file, do something
else
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
Here is how you can detect the change in the selected file name using JavaScript through the FileUpload onChange event.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" OnChange="CheckFileName(this)" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
JavaScript:
function CheckFileName(oFile)
{
PageMethods.FileNameChecker(oFile.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=f1.ClientID %>');
if (methodName == "FileNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'Duplicate filename.Sorry.';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = '';
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool FileNameChecker(string newFileName)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string x = newFileName.Substring(0,newFileName.LastIndexOf("\\"));
string tuname = newFileName.Substring(newFileName.LastIndexOf("\\") + 1, newFileName.Length - x.Length - 1);
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
bool found = false;
if (grpIDreader.HasRows)
found = true;
objsqlconn.Close();
return found;
}

checkbox_oncheckedchange event not firing in a gridview

I am trying to populate a gridview from a datatable in the code behind. In one of the columns dynamic checkboxes are generated. This is the code for gridview:
<asp:GridView ID="grdAdDetails" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField HeaderText="Ad Id" DataField="Ad Id" Visible="false"></asp:BoundField>
<asp:BoundField HeaderText="Ad Type" DataField="Ad Type" />
<asp:TemplateField HeaderText="Ad">
<ItemTemplate>
<img src='<%#Eval("Ad") %>' height="150px" width="150px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Ad Url" DataField="Ad Url" />
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
**<asp:CheckBox ID="chkAds" Checked='<%#((bool)Eval("Active"))%>' runat="server" OnCheckedChanged="chkAds_OnCheckedChanged" />**
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField HeaderText="Active" DataField="Active" />--%>
<asp:BoundField HeaderText="Node Id" DataField="Node Id" />
</Columns>
</asp:GridView>
and this is the datatable code from the code behind:
DataTable dt = new DataTable();
dt.Columns.Add("Ad Id", typeof(string));
dt.Columns.Add("Ad Type", typeof(string));
dt.Columns.Add("Ad", typeof(string));
dt.Columns.Add("Ad Url", typeof(string));
dt.Columns.Add("Active", typeof(bool));
dt.Columns.Add("Node Id", typeof(string));
DataRow dr = dt.NewRow();
con.Open();
SqlCommand cmd = new SqlCommand("[temp].[somename]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#nodeId", 1088);
cmd.Parameters.AddWithValue("#adType", 0);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
dr["Ad Id"] = reader[0].ToString();
dr["Ad Type"] = reader[1].ToString();
dr["Ad"] = reader[2].ToString();
dr["Ad Url"] = reader[3].ToString();
dr["Active"] =Convert.ToBoolean(reader[4]);
dr["Node Id"] = reader[5].ToString();
}
dt.Rows.Add(dr);
}
con.Close();
grdAdDetails.DataSource = dt;
grdAdDetails.DataBind();
checkbox onchanged code:
public void chkAds_OnCheckedChanged(object sender, EventArgs e)
{
int selRowIndex = ((GridViewRow)(((CheckBox)sender).Parent.Parent)).RowIndex;
CheckBox cb = (CheckBox)grdAdDetails.Rows[selRowIndex].FindControl("chkAds");
if (cb.Checked)
{
//some code here
}
}
When I check/uncheck the checkbox, the OnCheckedChanged event is not firing. Can anyone help with that?
I have added a sample here plz chk it.
view:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false"
OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:checkbox id="CheckBox1" runat="server" AutoPostBack="true" oncheckedchanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Name">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("fpath")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%#Eval("desc1")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtdesc" runat="server" Text='<%#Eval("desc1")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText="Edit">
<ControlStyle Width="50" />
</asp:CommandField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this record?');">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
using System;
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.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
String fname, fpath, desc;
String spath;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
if (!Page.IsPostBack)
{
LoadGrid();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//Check File is available in Fileupload control and then upload to server path
fname = FileUpload1.FileName;
spath = #"~\Uploaded\" + FileUpload1.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + FileUpload1.FileName;
desc = TextBox2.Text;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
FileUpload1.SaveAs(fpath);
}
//Store details in the SQL Server table
StoreDetails();
TextBox2.Text = "";
LoadGrid();
}
else
{
Label1.Text = "Please select file!";
}
}
void StoreDetails()
{
String query;
query = "insert into fileDet(fname,fpath,desc1) values('" + fname + "','" + spath + "','" + desc + "')";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}
void LoadGrid()
{
sqlcon.Open();
sqlcmd = new SqlCommand("select * from fileDet", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.DataBind();
}
sqlcon.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
LoadGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
LoadGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String ID;
ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
sqlcmd = new SqlCommand("select * from fileDet where ID='" + ID + "'", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (System.IO.File.Exists(Server.MapPath(dt.Rows[0][2].ToString())))
{
System.IO.File.Delete(Server.MapPath(dt.Rows[0][2].ToString()));
}
}
sqlcmd = new SqlCommand("delete from fileDet where ID='" + ID + "'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
string ID;
ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
FileUpload flname = (FileUpload)row.FindControl("FileUpload2");
if (flname.HasFile)
{
fname = flname.FileName;
spath = #"~\Uploaded\" + flname.FileName;
fpath = Server.MapPath("Uploaded");
fpath = fpath + #"\" + flname.FileName;
if (System.IO.File.Exists(fpath))
{
Label1.Text = "File Name already exists!";
return;
}
else
{
flname.SaveAs(fpath);
}
}
else
{
Label1.Text = "Please select file!";
}
TextBox desc1 = (TextBox)row.FindControl("txtdesc");
string query;
query = "update fileDet set fname='" + fname + "',fpath='" + spath + "',desc1='" + desc1.Text + "' where ID='" + ID + "'";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
GridView1.EditIndex = -1;
LoadGrid();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
// lblmsg.Text = GridView1.DataKeys[gr.RowIndex].Value.ToString();
//lblmsg.Text = "Hello";
}
}

Resources