Basically, I have a SQLDataSource that is a stored procedure that has two parameters (datetime). I have two calendars that set these parameters on click. I have checked the stored procedure and the parameters work, but the GridView is not showing the results of the stored procedure because the user has to click on the calendar to set parameters for a result. I think the GridView is just showing the stored procedure results without any parameters (so it's blank). This is my suspicion because I also have an "Export to Excel" button that exports the GridView to Excel and the Excel file is also blank after being downloaded.
I think I need to implement a button that refreshes the GridView so that the user can select the date parameters with the two calendars for the stored procedure which creates a result. The button would then refresh/update the GridView that only shows the initial blank result with the new stored procedure result. How do I create this "refresh button"?
For reference,
aspx.cs looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
GridView1.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=gvtoexcel.xls");
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
GridView1.AllowPaging = true;
GridView1.AllowSorting = true;
GridView1.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
fromDate = Calendar1.SelectedDate;
SqlDataSource1.SelectParameters[0].DefaultValue = fromDate.ToString();
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
toDate = Calendar2.SelectedDate;
SqlDataSource1.SelectParameters[1].DefaultValue = toDate.ToString();
}
}
}
And the .aspx looks like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" EnableEventValidation="false" %>
<!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>
<style type="text/css">
.style1
{
text-align: center;
}
.style2
{
text-align: left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style1" style="margin-left: 40px">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BIZ_DBConnectionString %>"
SelectCommand="Payrolldeduction" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DbType="DateTime" Name="fromDate" />
<asp:Parameter DbType="DateTime" Name="toDate" />
</SelectParameters>
</asp:SqlDataSource>
<div class="style1">
Payroll Report<br />
</div>
<div class="style2">
<br />
From:</div>
<asp:Calendar ID="Calendar1" runat="server"
onselectionchanged="Calendar1_SelectionChanged" style="text-align: left">
</asp:Calendar>
<div class="style2">
To:</div>
<asp:Calendar ID="Calendar2" runat="server" style="text-align: left">
</asp:Calendar>
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Export to Excel" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
onselectedindexchanged="Page_Load" AllowPaging="True">
<Columns>
<asp:BoundField DataField="INST_ID" HeaderText="INST_ID"
SortExpression="INST_ID" />
<asp:BoundField DataField="EMPLOYEE_ID" HeaderText="EMPLOYEE_ID"
SortExpression="EMPLOYEE_ID" />
<asp:BoundField DataField="HR_DEDUCTION_AND_BENEFITS_CODE"
HeaderText="HR_DEDUCTION_AND_BENEFITS_CODE"
SortExpression="HR_DEDUCTION_AND_BENEFITS_CODE" />
<asp:BoundField DataField="Column1" HeaderText="Column1" ReadOnly="True"
SortExpression="Column1" />
<asp:BoundField DataField="WITHHOLDING_LIABILITY_ACCOUNT_MASK"
HeaderText="WITHHOLDING_LIABILITY_ACCOUNT_MASK"
SortExpression="WITHHOLDING_LIABILITY_ACCOUNT_MASK" />
<asp:BoundField DataField="HR_DEDUCTION_AND_BENEFITS_ID"
HeaderText="HR_DEDUCTION_AND_BENEFITS_ID"
SortExpression="HR_DEDUCTION_AND_BENEFITS_ID" />
<asp:BoundField DataField="CHECK_DATE" HeaderText="CHECK_DATE"
SortExpression="CHECK_DATE" />
<asp:BoundField DataField="CHECK_NO" HeaderText="CHECK_NO"
SortExpression="CHECK_NO" />
<asp:BoundField DataField="FIN_INST_ACCT_ID" HeaderText="FIN_INST_ACCT_ID"
SortExpression="FIN_INST_ACCT_ID" />
<asp:BoundField DataField="Column2" HeaderText="Column2" ReadOnly="True"
SortExpression="Column2" />
<asp:BoundField DataField="HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE"
HeaderText="HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE"
SortExpression="HR_DEDUCTION_AND_BENEFIT_CYCLE_CODE" />
<asp:BoundField DataField="LENGTH" HeaderText="LENGTH"
SortExpression="LENGTH" />
<asp:BoundField DataField="EMPLOYEE_COMPUTED_AMOUNT"
HeaderText="EMPLOYEE_COMPUTED_AMOUNT"
SortExpression="EMPLOYEE_COMPUTED_AMOUNT" />
<asp:BoundField DataField="EMPLOYEE_BANK_ROUTING_NUMBER"
HeaderText="EMPLOYEE_BANK_ROUTING_NUMBER"
SortExpression="EMPLOYEE_BANK_ROUTING_NUMBER" />
<asp:BoundField DataField="EMPLOYEE_ACCOUNT_TYPE"
HeaderText="EMPLOYEE_ACCOUNT_TYPE" SortExpression="EMPLOYEE_ACCOUNT_TYPE" />
<asp:BoundField DataField="EMPLOYEE_ACCOUNT_NUMBER"
HeaderText="EMPLOYEE_ACCOUNT_NUMBER" SortExpression="EMPLOYEE_ACCOUNT_NUMBER" />
<asp:BoundField DataField="EMPLOYER_COMPUTED_AMOUNT"
HeaderText="EMPLOYER_COMPUTED_AMOUNT"
SortExpression="EMPLOYER_COMPUTED_AMOUNT" />
<asp:BoundField DataField="EMPLOYEE_GROSS_AMOUNT"
HeaderText="EMPLOYEE_GROSS_AMOUNT" SortExpression="EMPLOYEE_GROSS_AMOUNT" />
<asp:BoundField DataField="EMPLOYER_GROSS_AMOUNT"
HeaderText="EMPLOYER_GROSS_AMOUNT" SortExpression="EMPLOYER_GROSS_AMOUNT" />
<asp:CheckBoxField DataField="PAYROLL_EXCLUDE" HeaderText="PAYROLL_EXCLUDE"
SortExpression="PAYROLL_EXCLUDE" />
<asp:BoundField DataField="VOID_DATE" HeaderText="VOID_DATE"
SortExpression="VOID_DATE" />
<asp:BoundField DataField="BATCH_QUEUE_ID" HeaderText="BATCH_QUEUE_ID"
SortExpression="BATCH_QUEUE_ID" />
<asp:BoundField DataField="BATCH_CODE" HeaderText="BATCH_CODE"
SortExpression="BATCH_CODE" />
<asp:BoundField DataField="FY" HeaderText="FY" SortExpression="FY" />
<asp:BoundField DataField="END_DATE" HeaderText="END_DATE"
SortExpression="END_DATE" />
<asp:BoundField DataField="COMMENTS" HeaderText="COMMENTS"
SortExpression="COMMENTS" />
<asp:BoundField DataField="BATCH_CRITERIA_USED"
HeaderText="BATCH_CRITERIA_USED" SortExpression="BATCH_CRITERIA_USED" />
<asp:BoundField DataField="COLUMN_VALUE" HeaderText="COLUMN_VALUE"
SortExpression="COLUMN_VALUE" />
<asp:BoundField DataField="REPLACEMENT" HeaderText="REPLACEMENT"
SortExpression="REPLACEMENT" />
<asp:BoundField DataField="LAST_NAME" HeaderText="LAST_NAME"
SortExpression="LAST_NAME" />
<asp:BoundField DataField="FIRST_NAME" HeaderText="FIRST_NAME"
SortExpression="FIRST_NAME" />
<asp:BoundField DataField="MIDDLE_NAME" HeaderText="MIDDLE_NAME"
SortExpression="MIDDLE_NAME" />
</Columns>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
Thanks.
Update:
I somehow managed to make the dates from calendar selection stay put and act as parameters (the user now selects the calendar dates and then the confirm button / button2 which was previously the Export to Excel button which is now button3), but the GridView is not showing the stored procedure's results even with the parameters set. No errors are popping up either. What is going on?
Here's how the code looks now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
DateTime fmDate = new DateTime();
DateTime toDate = new DateTime();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BIZ_DBConnectionString"].ConnectionString;
SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource1.SelectCommand = "Payrolldeduction";
SqlDataSource1.SelectParameters.Clear();
FormParameter fmDate = new FormParameter("#Param1", Calendar1.SelectedDate.ToString());
FormParameter toDate = new FormParameter("#Param2", Calendar2.SelectedDate.ToString());
SqlDataSource1.SelectParameters.Add(fmDate);
SqlDataSource1.SelectParameters.Add(toDate);
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = true;
GridView1.AllowSorting = false;
GridView1.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=newexcelreport.xls");
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
GridView1.AllowPaging = true;
GridView1.AllowSorting = false;
GridView1.DataBind();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
fmDate = Calendar1.SelectedDate;
fromDate.Text = Calendar1.SelectedDate.ToString();
SqlDataSource1.SelectParameters[0].DefaultValue = fmDate.ToString();
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
toDate = Calendar2.SelectedDate;
SqlDataSource1.SelectParameters[1].DefaultValue = toDate.ToString();
}
}
}
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" EnableEventValidation="false" %>
<!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>
<style type="text/css">
.style1
{
text-align: center;
}
.style2
{
text-align: left;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style1" style="margin-left: 40px">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BIZ_DBConnectionString %>"
SelectCommand="Payrolldeduction" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DbType="DateTime" Name="fromDate" />
<asp:Parameter DbType="DateTime" Name="toDate" />
</SelectParameters>
</asp:SqlDataSource>
<div class="style1">
Payroll Report<br />
</div>
<div class="style2">
<br />
From:</div>
<asp:TextBox runat="server" ID="fromDate" Text=""></asp:TextBox>
<asp:Calendar ID="Calendar1" runat="server" style="text-align: left"> </asp:Calendar>
<div class="style2">
To:</div>
<asp:Calendar ID="Calendar2" runat="server" style="text-align: left">
</asp:Calendar>
<br />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Confirm" />
<br />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Export" />
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="true">
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
You NEVER call Page_Load as a GridView event handler. Beside the fact that, based on your code, it's doing nothing anyway, it is called every time your page posts back regardless of the button that caused the post back.
Your SqlDataSource select parameters should be Control Parameters that reference the 2 calendar controls. This means you do not need to handle the calendar's SelectionChanged events, it will be automatic. BUT...
Calendar Controls auto postback anyway, which means you need to validate the dates either by asp valdiation or in your stored procedure and only return a DataSet if the dates have any meaning.
As for your GridView - it will always try to refresh because you do this: DataSourceID="SqlDataSource1". In any asp databound control, when you set the DataSourceID property, your control will ALWAYS make a call to DataBind() on every postback.
Update 2015-03-02 ~1850EST
protected void Button2_Click(object sender, EventArgs e)
{
// validate the dates here then:
// If you MUST use Parameters over ControlParameters,
// then you need to assign the date here like this:
SqlDataSource1.SelectParameters("fromDate").DefaultValue = Calendar1.SelectedDate.ToString()
SqlDataSource1.SelectParameters("toDate").DefaultValue = Calendar2.SelectedDate.ToString()
// No need to force databind because in the markup you set the property
// DataSourceID="SqlDataSource1"
// This will force the Gridview to call DataBind() on each
// postback. And Control changed events (button click in this case)
// occur before DataBind() events
//###############################################################
//###############################################################
//None of this stuff is needed. It's already done in the markup:
//###############################################################
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BIZ_DBConnectionString"].ConnectionString;
SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource1.SelectCommand = "Payrolldeduction";
SqlDataSource1.SelectParameters.Clear();
FormParameter fmDate = new FormParameter("#Param1", Calendar1.SelectedDate.ToString());
FormParameter toDate = new FormParameter("#Param2", Calendar2.SelectedDate.ToString());
SqlDataSource1.SelectParameters.Add(fmDate);
SqlDataSource1.SelectParameters.Add(toDate);
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
//###############################################################
//###############################################################
}
Related
I am currently using Visual Studio to build my project and I'm having it automatically generate the Edit button. My Gridview allows for searching via a search box and a page only handles up to 10 rows. On the very first load of the Gridview, the Edit button and the accompanying Update and Cancel work perfectly fine. However, once I click on a new page, it fires these errors when I try to click Edit (the second error was when I somehow got the Update and Cancel button to show):
The GridView 'ProjectTable' fired event RowEditing which wasn't handled.
The GridView 'ProjectTable' fired event RowCancelingEdit which wasn't handled.
What is going on? Here is my aspx page:
<head runat="server">
<title></title>
<style>
.hiddencol
{
display: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="SearchBox" runat="server"></asp:TextBox>
<asp:DropDownList ID="SearchParameterList" runat="server">
<asp:ListItem Selected="True" Value="Project_Name">Project Name</asp:ListItem>
<asp:ListItem Value="Product">Product</asp:ListItem>
<asp:ListItem Value="Description">Description</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="SearchButton" runat="server" Text="Search" OnClick="SearchButton_Click" />
<asp:Button ID="ClearButton" runat="server" OnClick="ClearButton_Click" Text="Clear" />
<br />
<br />
<asp:GridView ID="ProjectTable" runat="server" Font-Names="Verdana,Arial" Font-Size="12px" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="PopulateProjectTable" AllowPaging="True" OnPageIndexChanging="ProjectTable_PageIndexChanging>
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="12px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="12px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<Columns>
<asp:BoundField DataField="ProjID" HeaderText="ProjID" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" SortExpression="ProjID" />
<asp:BoundField DataField="Project_Name" HeaderText="Project Name Value" ReadOnly="True" SortExpression="Project_Name" />
<asp:BoundField DataField="Product" HeaderText="Product" SortExpression="Product" ReadOnly="True" />
<asp:BoundField DataField="Product_Edit" HeaderText="Product (alternate)" SortExpression="Product_Edit" />
<asp:BoundField DataField="Description" HeaderText="Description" ReadOnly="True" SortExpression="Description" />
<asp:BoundField DataField="Description_Edit" HeaderText="Description (alternate)" SortExpression="Description_Edit" />
<asp:BoundField DataField="Comment" HeaderText="Comment Submission/Approval" SortExpression="Comment" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="PopulateProjectTable" runat="server"
ConnectionString="<%$ ConnectionStrings:ODSConnectionString %>"
SelectCommand="SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail]"
UpdateCommand="UPDATE [Pipeline_Detail] SET Product_Edit = #Product_Edit, Description_Edit= #Description_Edit, Comment = #Comment WHERE ProjID = #ProjID">
<UpdateParameters>
<asp:Parameter Name="ProjID"/>
<asp:Parameter Name="Product_Edit" Type="String"/>
<asp:Parameter Name="Description_Edit" Type="String"/>
<asp:Parameter Name="Comment" Type="String"/>
</UpdateParameters>
</asp:SqlDataSource>
</div>
</form>
And here is my code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SearchButton_Click(object sender, EventArgs e)
{
ProjectTable.PageIndex = 0;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE " + SearchParameterList.SelectedValue.ToString() + " LIKE '%" + SearchBox.Text + "%'";
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
}
protected void ClearButton_Click(object sender, EventArgs e)
{
ProjectTable.PageIndex = 0;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE Project_Name LIKE '%%'";
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
SearchBox.Text = "";
}
protected void ProjectTable_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ProjectTable.PageIndex = e.NewPageIndex;
ProjectTable.DataSourceID = null;
PopulateProjectTable.SelectCommand = "SELECT [Project_Name], [Product], [Product_Edit], [Description], [Description_Edit], [Comment], [ProjID] FROM [Pipeline_Detail] WHERE " + SearchParameterList.SelectedValue.ToString() + " LIKE '%" + SearchBox.Text + "%'" ;
ProjectTable.DataSource = PopulateProjectTable;
ProjectTable.DataBind();
}
}
You need to implement those events. In your markup you set auto generate edit button to true but you never implement the On Row Editing event and On Row Cancelling Edit event. Updating your markup to:
<asp:GridView ID="ProjectTable" runat="server" Font-Names="Verdana,Arial" Font-Size="12px" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="PopulateProjectTable" AllowPaging="True" OnPageIndexChanging="ProjectTable_PageIndexChanging" OnRowEditing="ProjectTable_OnRowEditing" OnRowCancelingEdit="ProjectTable_OnRowCancellingEdit">
and then add that method to your code behind:
protected void ProjectTable_OnRowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void ProjectTable_OnRowCancellingEdit(object sender, GridViewCancelEditEventArgs e)
{
}
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;
I am trying to use the DataTables Column Filter Add-on on a gridview table using an sql datasource but i am not coming up with any luck. I have the gridview render a header and footer but i can not add anything to the footer.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Glossary.aspx.cs" Inherits="Home.Glossary" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title spellcheck="true">Glossary</title>
<style type="text/css" media="all">
#import "DataTables-1.9.4/DataTables-1.9.4/media/css/jquery.dataTables_themeroller.css";
#form1 {
width: 100%;
}
</style>
<script src="DataTables-1.9.4/DataTables-1.9.4/media/js/jquery.js"></script>
<script src="DataTables-1.9.4/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
<script src="JQuery-DataTables-ColumnFilter/media/js/jquery.dataTables.columnFilter.js"></script>
<script>
$(document).ready(function () {
$('#<%=GridView1.ClientID%>').dataTable().columnFilter();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="background: #A0A0A0">
</div>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="TermText,DefNbr,DefVerNbr" DataSourceID="TedGlossary"
EnableSortingAndPagingCallbacks="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" ShowFooter="true"
AutoGenerateColumns="False" AutoGenerateEditButton="False" style="margin-right: 0px" Width="100%" Height="382px">
<Columns>
<asp:BoundField DataField="TermText" HeaderText="Term" ReadOnly="True" SortExpression="Term" />
<asp:BoundField DataField="DefNbr" HeaderText="Number" ReadOnly="True" SortExpression="DefinitionNumber" />
<asp:BoundField DataField="DefVerNbr" HeaderText="Version" ReadOnly="True" SortExpression="DefinitinonVersionNumber" />
<asp:BoundField DataField="DefText" HeaderText="Definition" SortExpression="Definition" />
<asp:BoundField DataField="AmplifyingExplanationText" HeaderText="Amplifying Explanation" SortExpression="AmplifyingExplanationText" />
<asp:BoundField DataField="SeeAlsoText" HeaderText="See Also" SortExpression="See Also" />
<asp:BoundField DataField="AuthoritativeSrcText" HeaderText="Authoritative Source" SortExpression="AuthoritativeSrcText" />
<asp:BoundField DataField="ScopeName" HeaderText="Scope" SortExpression="Scope" />
<asp:BoundField DataField="DomnName" HeaderText="Domain" SortExpression="Domain" />
<asp:BoundField DataField="GovernanceStateName" HeaderText="Governance State" SortExpression="GovernanceStateName" />
<asp:BoundField DataField="LastUpdtTimestamp" HeaderText="Last Updated" SortExpression="LastUpdtTimestamp" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="TedGlossary" runat="server" ConnectionString="<%$ ConnectionStrings:Glsry_Taylor %>" SelectCommand="SELECT * FROM [Glossary] ORDER BY [TermText]"></asp:SqlDataSource>
</form>
</body>
</html>
Here is the CS for the rendering
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Home
{
public partial class Glossary : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.PreRender += new EventHandler(GridView1_PreRender);
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (GridView1.Rows.Count > 0)
{
//forces grid to render thead/tbody/tfoot elements
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Here is the HTML output, there is too much for the site to handle i put in pastebin the link is included
http://pastebin.com/2qh2eXWY
In order to add anything to the footer, you need to use TemplateField controls rather than BoundField controls. See http://www.dreamincode.net/forums/topic/222381-insert-data-using-gridview-footerrow/ for an example of how to do this. One thing to note though, the HTML generated by the GridView control will use <td> elements in the footer rather than <th> elements as expected by the DataTables documentation.
i am working on Asp.Net with C#-4.0 .
I want to get Input from end user in a GridView. Like
in DropDownList or in TextBox i enters some value and clicks on Add then new record will add but previous data was lost.
the Problem is when i change value of controls, it not saves in DataTable to which it is binded. How can i save this value to DataTable. What code i have missed here ?
designer code :
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SaleOrder.aspx.cs" Inherits="Transactions_SaleOrder" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FormHeader" Runat="Server">
<p>Sale Order</p>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="FormBody" Runat="Server">
<table class="style1">
<tr>
<td>
<asp:Label ID="lblDate" runat="server" Text="Date : "></asp:Label>
<asp:TextBox ID="txtSODate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="txtSODate_CalendarExtender" runat="server"
Enabled="True" TargetControlID="txtSODate" Format="dd/MM/yyyy" PopupButtonID="ImageButton1">
</asp:CalendarExtender>
<asp:MaskedEditExtender ID="txtSODate_MaskedEditExtender" runat="server"
Enabled="True" Mask="99/99/9999" MaskType="Date" TargetControlID="txtSODate">
</asp:MaskedEditExtender>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/Calendar_scheduleHS.png" />
</td>
</tr>
<tr>
<td>
Shift :
<asp:DropDownList ID="DropDownList1" runat="server" Width="300px">
<asp:ListItem Value="Morning">MORNING</asp:ListItem>
<asp:ListItem Value="EVENING"></asp:ListItem>
<asp:ListItem Value="OTHERS"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" Width="300"
DataSource='<%# dtProductMaster %>'
DataTextField="PDescr"
DataValueField="PID"
>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtQuan" runat="server" MaxLength="5" style="text-align:right" Text='<%# BIND("QUAN") %>'></asp:TextBox>
<asp:MaskedEditExtender ID="txtQuan_MaskedEditExtender" runat="server" Enabled="True"
Mask="99999" TargetControlID="txtQuan">
</asp:MaskedEditExtender>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:ButtonField CommandName="ADD" Text="Add" />
<asp:ButtonField CommandName="DELETE" Text="Delete" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" Width="58px" />
</td>
</tr>
</table>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="FormFooter" Runat="Server">
</asp:Content>
C# Code behind it :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Transactions_SaleOrder : System.Web.UI.Page
{
internal DataTable dtProductMaster_;
internal DataTable dtProductMaster
{
get
{
if (dtProductMaster_ == null)
{
clsData d = new clsData();
d.Select("select PID, PEDESCR2 + ' ' + PEDESCR3 as PDescr From TBLPROD_MAST");
dtProductMaster_ = d.DataTable;
}
return dtProductMaster_;
}
}
DataTable dtProductDet
{
get
{
if (ViewState["dtProductDet"] != null)
{
return (DataTable)ViewState["dtProductDet"];
}
else
{
return null;
}
}
set
{
ViewState["dtProductDet"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
}
GridView1.DataSource = dtProductDet;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToUpper())
{
case "ADD":
dtProductDet.Rows.Add(0, "", 0);
break;
case "DELETE":
dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
break;
}
}
}
how can i achieve my aim.
The answer has already been given in previous comments. To spell it out...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
GridView1.DataSource = dtProductDet;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName.ToUpper())
{
case "ADD":
dtProductDet.Rows.Add(0, "", 0);
break;
case "DELETE":
dtProductDet.Rows.RemoveAt(Convert.ToInt32(e.CommandArgument));
break;
}
GridView1.DataBind();
}
I have got the solution.
The problem is, when i am editing value in DropDownList or in TextBox, its value is not saving back to DataTable which is bind with GridView and TextBox and DropDownList.
There is no automatic way to do this, so we have to write manual code to save values back to DataTable.
When i asked the question add button was in GridViewColumn and it was command Column, now i have added a button in GridView Footer.
So when i click on "Add new row" button, page is posted back, at first page load event fires and then Button_Click event fires. I have add code on Page.Load event, if page is posted back then pick data from GridView and Save it to DataTable.
Nextly Button_click event fires, so a new row adds in DataTable and DataTable will assign in DataSource of GridView and DataBind method executes and re-generates GridView.
I have a DropDownList which is also bind to a different DataTable other than GridView, so that after DataBind() i have to select manually value in DropDownList as per saved in DataTable of GridView.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txtSODate.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
//--
dtProductDet = new DataTable("dtProductDet");
dtProductDet.Columns.Add("PID", typeof(int));
dtProductDet.Columns.Add("PName", typeof(string));
dtProductDet.Columns.Add("Quan", typeof(decimal));
dtProductDet.Rows.Add(0,"",0);
//--
SetGridViewSource();
}
else
{
DataTable dtPD = dtProductDet;
DropDownList ddlProd = null;
if (GridView1.Rows.Count > 0)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
dtPD.Rows[i]["PID"] = Convert.ToInt32(ddlProd.SelectedItem.Value);
dtPD.Rows[i]["PName"] = ddlProd.SelectedItem.Text;
dtPD.Rows[i]["QUAN"] = ((TextBox)GridView1.Rows[i].Cells[gvci_Quan].FindControl("txtQuan")).Text;
}
}
dtProductDet = dtPD;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
dtProductDet.Rows.Add(0, "", 0);
DataTable dtPDet = dtProductDet;
GridView1.DataSource = dtPDet;
GridView1.DataBind();
DropDownList ddlProd = null;
DataRow drFind = null;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
ddlProd = (DropDownList)GridView1.Rows[i].Cells[gvci_Prod].FindControl("ddlProduct");
drFind = dtProductMaster.Rows.Find(dtPDet.Rows[i]["PID"]);
if(drFind != null)
{
ddlProd.SelectedIndex = dtProductMaster.Rows.IndexOf(drFind);
}
}
}
I'm trying to fetch the data from the gridview according to the row I select for deletion.
I tried this,
string fileName = grdUploadedFiles.Rows[e.RowIndex].Cells[2].ToString();
but it shows the string,
System.Web.UI.WebControls.DataControlFieldCell
What exactly can I do to fetch the filename that I have inserted to the gridview.
Also, this field is not the DataKey.
If your cell not contain any control like label then try this
string fileName = grdUploadedFiles.Rows[e.RowIndex].Cells[2].Text;
You should be calling .Text for the value, per MSDN documentation.
Generally speaking .ToString is overridden by default for Value types. Reference types generally don't override .ToSting with their "values" (what you would commonly access when calling that class).
Here is an example from MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void CustomersGridView_RowDeleting
(Object sender, GridViewDeleteEventArgs e)
{
TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
if (cell.Text == "Beaver")
{
e.Cancel = true;
Message.Text = "You cannot delete customer Beaver.";
}
else
{
Message.Text = "";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>GridView RowDeleting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
GridView RowDeleting Example
</h3>
<asp:Label ID="Message" ForeColor="Red" runat="server" />
<br />
<asp:GridView ID="CustomersGridView" runat="server"
DataSourceID="CustomersSqlDataSource"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
OnRowDeleting="CustomersGridView_RowDeleting"
DataKeyNames="CustomerID,AddressID">
<Columns>
<asp:BoundField DataField="FirstName"
HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City"
SortExpression="City" />
<asp:BoundField DataField="StateProvince" HeaderText="State"
SortExpression="StateProvince" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID,
SalesLT.CustomerAddress.AddressID,
SalesLT.Customer.FirstName,
SalesLT.Customer.LastName,
SalesLT.Address.City,
SalesLT.Address.StateProvince
FROM SalesLT.Customer
INNER JOIN SalesLT.CustomerAddress
ON SalesLT.Customer.CustomerID =
SalesLT.CustomerAddress.CustomerID
INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID =
SalesLT.Address.AddressID"
DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID =
#CustomerID and AddressID = #AddressID"
ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
<DeleteParameters>
<asp:Parameter Name="AddressID" />
<asp:Parameter Name="CustomerID" />
</DeleteParameters>
</asp:SqlDataSource>
</form>
</body>
</html>