Handling Multiple GridViews in ASP.Net and C# - c#

I Have a Table column Called Status which takes three Values 1, 2 or 3. Now, I want to Display another column Name1 in either of the three GridViews depending on the Status. Also I have link buttons which Redirect to different web forms.
This is the output I'm Getting. The ID of this GridView is GridView1
This is the code I've used
Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
body{
font-family:Arial;
font-size:10px;
}
td,th{
height:25px;
width:100Px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<hr />
<asp:GridView ID="GridView" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile1"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
String statusVariable= string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//lb1.Text = "<b><font color=Brown>" + "WELLCOME ADMIN:: " + "</font>" + "<b><font color=red>" + Session["name"] + "</font>";
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt;
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Select Name1,Status from TBL_MST_ALL2";
cmd.Connection = con;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
{
while (reader.Read())
{
if (reader["Status"].ToString() == "3")
{
GridView.DataSource = reader;
GridView.DataBind();
}
else if (reader["Status"].ToString() == "2")
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
else if (reader["Status"].ToString() == "1")
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
con.Close();
}
}
}
}
}
protected void EditFile(object sender, EventArgs e)
{
Response.Redirect("EditResume.aspx");
}
protected void EditFile1(object sender, EventArgs e)
{
Response.Redirect("EditResume1.aspx");
}
}
However, all the data is being displayed in GridView1 regardless of the Status.

Related

I have a button in my item template and I want to program it so that it directs me to that specific job details

I have a page where I list all jobs. I have to program a button so that when I click on it, it directs me to that specific job details. How can I do that. I have tried navigateUrl but when I click on the button, nothing happens.
Here is my code for my item template
<asp:ListView ID="lsvJob" runat="server">
<ItemTemplate>
<div class="nf-item branding coffee spacing">
<div class="col-md-6 col-lg-4 mb-30">
<div class="service_box">
<figure>
<asp:Image ID="imgposter" ImageUrl='<%# Eval("HO_Image", "~/Images/{0}") %>'
runat="server" Height="300px" Width="300px" ImageAlign="Top" />
</figure>
<h3><%#Eval("Job_Name") %></h3>
<p>
<b>Employer Name:</b> <%# Eval("HO_LastName") %> <%# Eval("HO_FirstName") %>
<br />
<b>Email Address:</b> <%# Eval("HO_Email") %>
</p>
<asp:LinkButton ID="lnkmovdetails" runat="server" Text="View Details"
NavigateUrl='<%# Eval("Job_ID","~/jobdetails.aspx?id={0}")%>' CommandName="btnAccess" CssClass="btn btn-info"></asp:LinkButton>
</div>
</div>
</div>
</ItemTemplate>
</asp:ListView>
code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
namespace moCoolMaid
{
public partial class listjob : System.Web.UI.Page
{
private string _conString =
WebConfigurationManager.ConnectionStrings["MaidCS"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// Create Connection
using (SqlConnection con = new SqlConnection(_conString))
{
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = " SELECT tblHO.*, tblJob.* FROM tblHO, tblJob WHERE tblJob.HO_ID=tblHO.HO_ID";
//Create DataReader
SqlDataReader reader;
con.Open();
reader = cmd.ExecuteReader();
//Bind the reader to the repeater control
lsvJob.DataSource = reader;
lsvJob.DataBind();
con.Close();
}
}
}
}
Code in my jobdetail web form
<asp:DetailsView ID="dsvJob" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="10" GridLines="Vertical">
<AlternatingRowStyle BackColor="Gainsboro" />
<EditRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField DataField="Job_Name" HeaderText="Job_Name" SortExpression="Job_Name" />
<asp:BoundField DataField="Job_Desc" HeaderText="Job_Desc" SortExpression="Job_Desc" />
<asp:BoundField DataField="Job_Salary" HeaderText="Job_Salary" SortExpression="Job_Salary" ItemStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Deadline_Date" HeaderText="Deadline_Date" SortExpression="Deadline_Date" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Min_Experience" HeaderText="Min_Experience" SortExpression="Min_Experience" />
<asp:BoundField DataField="Min_Qualification" HeaderText="Min_Qualification" SortExpression="Min_Qualification" />
</Fields>
<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" />
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MaidCS %>" SelectCommand="SELECT [Job_Name], [Job_Desc], [Job_Salary], [Deadline_Date], [Type], [Min_Experience], [Min_Qualification] FROM [tblJob]"></asp:SqlDataSource>
remove navigateUrl property from LinkButton and below one.
PostBackUrl="imagepage.aspx?v=<%#Eval("id") %>"
from query string you will get jobID. read JobId and display record.
Thanks, hope this will help you :)
Command Name does not work like this. Use below code for redirection
<asp:LinkButton ID="lnkmovdetails" runat="server" Text="View Details" PostBackUrl='~/jobdetails.aspx?id=<%#Eval("Job_ID") %>' CssClass="btn btn-info" />

c# asp net updatepanel cause page refresh

I have a simple gridview with image button to update value of one of gridview column, by problem is whenever I click the image button it refresh the wholw page and I want the gridview only to be refreshed with updated value, I tried using UpdatePanel but it also refresh the whole page,
any help will be apprechiated.
aspx code:
<form id="form1" runat="server" >
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" PageSize="5">
<Columns >
<asp:BoundField DataField="req_id" HeaderText="request ID" SortExpression="req_id" />
<asp:BoundField DataField="req subject" HeaderText="request subject" SortExpression="req_subject" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
aspx.cs code:
protected void Button_update(object sender, ImageClickEventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(#"Data Source= DESKTOP-U9437PU; initial Catalog = Mydb; Integrated Security =True;"))
{
sqlCon.Open();
string sql = "update requests_table set stat_id = '2' where req_id ='" 5 "'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
sqlCon.Close();
}
GridView1.DataBind();
}
You need to set UpdateMode Conditional:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button_update" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" PageSize="5">
<Columns >
<asp:BoundField DataField="req_id" HeaderText="request ID" SortExpression="req_id" />
<asp:BoundField DataField="req subject" HeaderText="request subject" SortExpression="req_subject" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Then you should work call UpdatePanel1.Update(); as following:
protected void Button_update(object sender, ImageClickEventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(#"Data Source= DESKTOP-U9437PU; initial Catalog = Mydb; Integrated Security =True;"))
{
sqlCon.Open();
string sql = "update requests_table set stat_id = '2' where req_id ='" 5 "'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
sqlCon.Close();
}
GridView1.DataBind();
UpdatePanel1.Update();
}
Try this:
<asp:ImageButton ID="Button_update" runat="server" CommandArgument='<%# Bind("req_id") %>' CssClass="yourCssClassIsNeedIt" ImageUrl="Images/under.png" OnClick="btn_under" UseSubmitBehavior="false" OnClientClick="javascript:void(0);" />
And this
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">

Custom pagination on itemtemplate using gridview

I want to apply custom pagination to my gridview which contains itemtemplate
which has a image that comes from the database
I have tried with clientid mode static but that didnt work out
My Procedure:-
create procedure sp_BookingByPageSize
#pageNo int,
#NoOfRecord int,
#TotalRecord int output
as
select #TotalRecord =
count(*) from tblDiscount
select * from
(
select
Row_number() over
(order by r.bookingid asc)
as RowNo,
r.BookingId,
u.Fullname,
h.hotelName,
case when r.bookingstatus=1 then 'Confirmed'
when r.BookingStatus=0 then 'Cancelled'
end as Booking_Status
,r.Check_In,r.Check_Out,r.NoOfGuests,ro.RoomTypeName,r.NoOfRoomsBooked,r.NationalID,r.Amount from tblReservation as r inner join
tblHotel as h on r.HotelId=h.HotelID
inner join tblUser as u
on u.UId=r.UId inner join tblRooms as ro on ro.RoomsID=r.RoomType)
AS Tab
where tab.RowNo between((#PageNo-1)*#NoOfRecord)+1 and (#PageNo*#NoOfRecord)
order by 2 asc
return
My aspx file:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="table table-condensed" runat="server" OnRowCommand="GridView1_RowCommand" DataKeyNames="bookingid" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:ButtonField CommandName="download"
ControlStyle-CssClass="btn btn-info" ButtonType="Button"
Text="Download Invoice" HeaderText="Invoice" />
<asp:BoundField DataField="bookingid" HeaderText="Booking ID" />
<asp:BoundField DataField="hotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Booking_Status" HeaderText="Booking Status" />
<asp:BoundField DataField="Check_In" HeaderText="Check In" />
<asp:BoundField DataField="Check_Out" HeaderText="Check Out" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Room Type" />
<asp:BoundField DataField="NoOfRoomsBooked" HeaderText="No of Rooms Booked" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:TemplateField HeaderText="NationalID">
<ItemTemplate>
<asp:Image ID="Image1" CssClass="default" runat="server"
ImageUrl='<%# "data:Image/jpg;base64,"
+ Convert.ToBase64String((byte[])Eval("NationalID")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField runat="server" ID="hiddenprimary" />
<div style="margin-left: 1500px;">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
MyCode behinde:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HotelBAL;
namespace HotelReservation.Views
{
public partial class AdminViewBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData(1, 5);
}
AddpaggingButton();
}
private void PopulateData(int pageNo, int noOfRecord)
{
GridView1.DataSource = BookingBal.PopulateData(pageNo, noOfRecord);
GridView1.DataBind();
ViewState["TotalRecord"] = BookingBal.getTotalRecord1();
ViewState["NoOfRecord"] = BookingBal.getNoOfRecord1();
}
private void AddpaggingButton()
{
int totalRecord = 0;
int noOfRecord = 0;
totalRecord = ViewState["TotalRecord"] != null ? (int)ViewState["TotalRecord"] : 0;
noOfRecord = ViewState["NoOfRecord"] != null ? (int)ViewState["NoOfRecord"] : 0;
int pages = 0;
if (totalRecord > 0 && noOfRecord > 0)
{
pages = (totalRecord / noOfRecord) + ((totalRecord % noOfRecord) > 0 ? 1 : 0);
for (int i = 0; i < pages; i++)
{
Button b = new Button();
b.Text = (i + 1).ToString();
b.CommandArgument = (i + 1).ToString();
b.ID = "Button_" + (i + 1).ToString();
b.CssClass = "btn btn-outline-warning";
b.Click += new EventHandler(this.b_click);
Panel1.Controls.Add(b);
}
}
}
private void b_click(object sender, EventArgs e)
{
//this is for get data from database from clicking button
string pageNo = ((Button)sender).CommandArgument;
PopulateData(Convert.ToInt32(pageNo), 5);
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
}
}
Here b_click should work but it is not working any help would be appreciated as I am new to this custom paging
I myself solved the problem by using a generic handler
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="table table-condensed" runat="server" OnRowCommand="GridView1_RowCommand" DataKeyNames="bookingid" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:ButtonField CommandName="download"
ControlStyle-CssClass="btn btn-info" ButtonType="Button"
Text="Download Invoice" HeaderText="Invoice" />
<asp:BoundField DataField="bookingid" HeaderText="Booking ID" />
<asp:BoundField DataField="hotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Booking_Status" HeaderText="Booking Status" />
<asp:BoundField DataField="Check_In" HeaderText="Check In" />
<asp:BoundField DataField="Check_Out" HeaderText="Check Out" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Room Type" />
<asp:BoundField DataField="NoOfRoomsBooked" HeaderText="No of Rooms Booked" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:BoundField HeaderText="Image" DataField="NationalID" Visible="false" />
<asp:TemplateField HeaderText="NationalID" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "imageHandler.ashx?bookingId="+ Eval("bookingId") %>'
Height="150px" Width="150px" />
<%-- <asp:Image ID="Image1" CssClass="default" runat="server"
ImageUrl='<%# "data:Image/jpg;base64,"
+ Convert.ToBase64String((byte[])Eval("NationalID")) %>' />--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField runat="server" ID="hiddenprimary" />
<div style="margin-left: 1500px;">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace HotelReservation.Views
{
/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["bookingId"];
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyProjectConnection"].ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select NationalID from tblReservation where bookingid=" + imageid, connection);
command.CommandType = CommandType.Text;
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

How to download pdf file using asp.net?

I upload file and stored in Data folder in server
File path:
Project Name
|_bin
|_css
|_Data
|_Mohamedfaisal.pdf
this is my asp.net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
namespace Expatriates {
public partial class FileUploadForm: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void Button1_Click(object sender, EventArgs e) {
if (FileUpload1.HasFile) {
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/") + FileUpload1.FileName);
}
DataTable dt = new DataTable();
dt.Columns.Add("File", typeof(string));
dt.Columns.Add("size", typeof(string));
dt.Columns.Add("type", typeof(string));
foreach(string strFile in Directory.GetFiles(Server.MapPath("~/Data/"))) {
FileInfo fi = new FileInfo(strFile);
dt.Rows.Add(fi.Name, fi.Length, fi.Extension);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Download") {
Response.Clear();
Response.Write(e.CommandArgument);
Response.ContentType = "application/octect-stream";
Response.AppendHeader("content-disposition", "filename=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/Data/") + e.CommandArgument); // error occured
Response.End();
}
}
}
}
Front End asp.net
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadForm.aspx.cs" Inherits="Expatriates.FileUploadForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-family:Arial;">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" Text='<%# Eval("File") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Size" HeaderText="Size in Bytes" />
<asp:BoundField DataField="Type" HeaderText="File Type" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
my front end design
UI design
when I click that link it shows that following error message
An exception of type 'System.IO.DirectoryNotFoundException' occurred
in mscorlib.dll but was not handled in user code
Additional information: Could not find a part of the path 'F:\Visual
Studio Project\Expatriates\Expatriates\Data\'.
Uploading file is working perfectly, But I am not getting a download.
You don't supply a commandArgument for your RowCommand event. Change
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" Text='<%# Eval("File") %>'></asp:LinkButton>
to
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Eval("File") %>' Text='<%# Eval("File") %>'></asp:LinkButton>
The only reason your code could fail would be if e.CommandArgument doesn't have a valid file name. I think the Command Argument isn't being passed for some reason, please look into your markup.
You have to explicitly specify CommandArgument for a LinkButton like this:
CommandArgument='<%# Eval("File") %>'

Visual Studio 12 - Gridview inserting footer row on submit

I have a gridview that I need a footer row inserted with the data from a textbox when the user hits submit. I have tried over and over and I can not get past the following error:
Object reference not set to an instance of an object. The error is flagged on the Textbox AddName line of code in the code behind.
Here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="WorkOrder.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" type="text/css" />
<link href="msgBoxLight.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Width="1020px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/mast_left.png" />
</asp:Panel>
</div>
<div class="Section"> <hr /><h2>
Online Work Order Form - (Admin)</h2>
</div>
<br />
<asp:Label ID="Label2" runat="server" Text="Select data you want to view and click the submit button:" CssClass="label"></asp:Label><br /><br />
<div>
<asp:GridView ID="GridViewAdmin" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource1" DataKeyNames="WO_ID" EnableModelValidation="True"
>
<Columns>
<asp:BoundField DataField="WO_ID" HeaderText="WO_ID" ReadOnly="True" SortExpression="WO_ID" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Job_Title" HeaderText="Job_Title" ReadOnly="True" SortExpression="Job_Title" />
<asp:BoundField DataField="Job_Assigned_To" HeaderText="Job_Assigned_To" SortExpression="Job_Assigned_To" />
<asp:CheckBoxField DataField="Completed" HeaderText="Completed" SortExpression="Completed" />
<asp:BoundField DataField="Completed_Date" HeaderText="Completed_Date" SortExpression="Completed_Date" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT [WO_ID], [Name], [Job_Type], [Job_UpdateName], [Job_Title], [Job_Description], [Job_Assigned_To], [Completed], [Completed_Date], [Notes] FROM [WO_Submission_Details]"
UpdateCommand="UPDATE [WO_Submission_Details] SET [Job_Assigned_To] = #Job_Assigned_To, [Completed] = #Completed, [Completed_Date] = #Completed_Date, [Notes] = #Notes WHERE [WO_ID] = #WO_ID">
</asp:SqlDataSource>
</div>
<br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AdminReport.aspx">Work Order Report</asp:HyperLink>
<br />
<br />
<hr />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter name below to add to Marketing employee table" CssClass="label"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Name:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Email:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<br /><br />
<asp:GridView ID="GridViewStaff" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="5"
DataSourceID="SqlDataSource2" datakeynames="ID" AllowSorting="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" text='<%#Eval("Email")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT * FROM [Marketing_Staff]" InsertCommand="INSERT INTO [Marketing_Staff] ([Name], [Email]) VALUES (#Name, #Email)">
<InsertParameters>
<asp:Parameter Type="String" Name="Name"></asp:Parameter>
<asp:Parameter Type="String" Name="Email"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text;
using System.IO;
namespace WorkOrder
{
public partial class Admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindgridView();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox AddName = GridViewStaff.FooterRow.FindControl("txtAddName") as TextBox;
// Response.Write(AddName.Text);
//TextBox Email = GridViewStaff.FooterRow.FindControl("txtAddEmail") as TextBox;
SqlDataSource2.InsertParameters["Name"].DefaultValue = txtAddName.Text;
// SqlDataSource2.InsertParameters["Email"].DefaultValue = txtAddEmail.Text;
SqlDataSource2.Insert();
// ExecuteInsert(txtAddName.Text);
txtAddName.Text = "";
txtAddEmail.Text = "";
}
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ZSC_WorkOrdersConnectionString"].ConnectionString;
}
public void bindgridView()
{
try
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string query = "Select * WO_ID, Name, Job_Type, Job_UpdateName, Job_Title, Job_Description, Job_Assigned_To, Completed, Completed_Date, Notes FROM WO_Submission_Details";
DataSet ds = new DataSet();
SqlDataAdapter sqldt = new SqlDataAdapter(query, conn);
sqldt.Fill(ds);
GridViewAdmin.DataSource = ds;
GridViewAdmin.DataBind();
if (ViewState["delRows"] != null)
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
//create the javascript array in the client side
//push the deleted row indexes from c# array to javascript array
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var indexArray = new Array;");
for (int i = 0; i < itemsLength; i++)
{
sb.Append("indexArray.push('" + delIndices[i] + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "arrayScript", sb.ToString());
//call the deleteRow function on the client side
this.ClientScript.RegisterStartupScript(typeof(Page), "del", "javascript:deletegrdvwRow()", true);
}
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewAdmin.EditIndex = e.NewEditIndex;
}
protected void GridViewAdmin_RowCancelingEdit(object sender, EventArgs e)
{
GridViewAdmin.EditIndex = -1;
}
protected void GridViewAdmin_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " ")
{
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if ((field.DataField != "Job_Assigned_To") && (field.DataField != "Completed") && (field.DataField != "Completed_Date") && (field.DataField != "Notes"))
field.ReadOnly = true;
}
}
}
protected void GridViewAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GridViewAdmin.PageIndex = e.NewPageIndex;
//while moving to the next page, clear the viewstate
ViewState["delRows"] = null;
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridViewAdmin.Rows[e.RowIndex];
//i set datakeys="ProductName,ProductID" in gridview in aspx page
//datakeys[rowindex][1]->refers to productid which is primary key.
string WOID = GridViewAdmin.DataKeys[row.RowIndex][0].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
TextBox JobAssignedTo = (TextBox)row.FindControl("txtJobAssignedTo");
CheckBox txtCompleted = (CheckBox)row.Cells[1].Controls[0];
TextBox CompletedDate = (TextBox)row.Cells[2].Controls[0];
TextBox Notes = (TextBox)row.Cells[3].Controls[0];
//write your logic here to update the data into the database
conn.Open();
SqlCommand cmd = new SqlCommand("update WO_Submission_Details set Job_Assigned_To='" + JobAssignedTo.Text + "',Completed='" + txtCompleted.Checked + "',Completed_Date='" + CompletedDate.Text + "',Notes='" + Notes.Text + "'where WO_ID='" + WOID + "'", conn);
//SqlCommand cmd = new SqlCommand("update duplicating_request_table set Completed_By=#CompletedBy WHERE Job_No=#JobNo");
cmd.ExecuteNonQuery();
conn.Close();
GridViewAdmin.EditIndex = -1;
//those rows which are deleted previously while updating store it's indexs
if (ViewState["delRows"] == null)
{
int[] delIndices = new int[12];
delIndices[0] = e.RowIndex;
ViewState["delRows"] = delIndices;
}
else
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
delIndices[itemsLength] = e.RowIndex;
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
}
}
It looks like your SqlDataSource2 is causing the error. Please double check that both Name and Email are of DB type string in your DB.
In your ASPX SqlDataSource2 make the following changes:
<InsertParameters>
<asp:QueryStringParameter Name="Name" QueryStringField="Name" DbType=String />
<asp:QueryStringParameter Name="Email" QueryStringField="Email" DbType=String />
</InsertParameters>
In your C# Code-Behind, change to this:
SqlDataSource2.InsertParameters[0].DefaultValue = txtAddName.Text;

Categories

Resources