How to fetch data from gridview row that is selected? - c#

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>

Related

GridView Asp .Net-Changing the selected value of a second drop down list based on value of first drop Down in same column

I'm new to ASP.NET and C#. I have a Grid View With Drop-Down-list.For Instance if the Grid View is like this,
<!DOCTYPE html>
<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" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" SortExpression="Designation" />
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="City" DataValueField="City">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CS %>" SelectCommand="SELECT [City] FROM [EmployeeDetails]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CS %>" SelectCommand="SELECT [ID], [Name], [Designation] FROM [EmployeeDetails]"></asp:SqlDataSource>
</form>
And In Column City,If suppose I select Mumbai in first DropDown, I want rest of the Dropdownlists in the column City to automatically change to Mumbai.
How to do that?
Change as below in you aspx file,
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="City" DataValueField="City" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
In you aspx.cs file,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList selectedDropDown = (DropDownList)sender;
foreach(GridViewRow gRow in GridView1.Rows)
{
DropDownList ddlCity = (DropDownList)gRow.FindControl("DropDownList1");
ddlCity.SelectedValue = selectedDropDown.SelectedValue;
}
}
This should work for all the drop down.
If you want it to work only for First Dropdown then, Use the condition as below.
if (((GridViewRow)selectedDropDown.Parent.Parent).RowIndex == 0)
{
foreach (GridViewRow gRow in GridView1.Rows)
{
DropDownList ddlCity = (DropDownList)gRow.FindControl("DropDownList1");
ddlCity.SelectedValue = selectedDropDown.SelectedValue;
}
}

Button to Refresh GridView?

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();
//###############################################################
//###############################################################
}

GridView not filtering results

I am attaching a SqlDataSource to a grid view.
Inside my SqlDataSource I use control parameters to filter the data, I have a button to filter the data using the text inside the textboxes.
The main problem is that nothing is being filtered.
Here is my aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Template.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head_breadcrumb" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentInfoBarName" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentInfoBarApprovalStatus" runat="server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="ContentInfoBarState" runat="server">
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="content" runat="server">
<tr>
<td width="100" align="right" bgcolor="#eeeeee" class="header1">Power Web</td>
<td align="center" bgcolor="#FFFFFF">
<asp:TextBox ID="txtNB" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSystem" runat="server"></asp:TextBox>
<asp:TextBox ID="txtObjectID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtObjectDescription" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" />
<asp:GridView ID="gvwExample" runat="server" OnClick="filter" AutoGenerateColumns="False" DataSourceID="GridDataSource" OnRowDataBound="gvwExample_RowDataBound" CssClass="basix" >
<columns>
<asp:BoundField DataField="NB" HeaderText="NB" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="CLevel" HeaderText="CLevel" />
<asp:BoundField DataField="CC Host" HeaderText="CC Host" />
<asp:BoundField DataField="System" HeaderText="System" />
<asp:BoundField DataField="Object Type" HeaderText="Object Type" />
<asp:BoundField DataField="Object ID" HeaderText="Object ID" />
<asp:BoundField DataField="Object Description" HeaderText="Object Description" />
<asp:BoundField DataField="Excl Mngr" HeaderText="Excl Mngr" />
</columns>
</asp:GridView>
<asp:SqlDataSource ID="GridDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:PowerWeb%>"
SelectCommand="SELECT * FROM Table1" FilterExpression="NB LIKE '{0}%' AND System LIKE '{1}%' AND Object ID LIKE '{2}%' AND Object Description LIKE '{3}%'">
<FilterParameters>
<asp:ControlParameter Name="NB" ControlID="txtNB" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="System" ControlID="txtSystem" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="Object ID" ControlID="txtObjectID" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" />
<asp:ControlParameter Name="Object Description" Type="String" ControlID="txtObjectDescription" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
<asp:label ID="lblStatus" runat="server"></asp:label></td>
</tr>
</asp:Content>
And here is my code behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void gvwExample_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "Excl Mngr");
if (e.Row.Cells[index].Text == "False")
{
e.Row.Cells[index].Text = "";
}
else if(e.Row.Cells[index].Text == "True")
{
e.Row.Cells[index].Text = "Yes";
}
}
}
int GetColumnIndexByName(GridViewRow row, string SearchColumnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(SearchColumnName))
{
break;
}
}
columnIndex++;
}
return columnIndex;
}
public void filter(Object sender, EventArgs e)
{
gvwExample.DataSource = GridDataSource;
gvwExample.DataBind();
}
}
EDIT:
The contentplaceholder named content is inside this on my master page:
<asp:UpdatePanel ID="updateMain" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:ContentPlaceHolder ID="content" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
Is because this?
Have you tried to remove the UpdatePanel from the Master Page and add it to your page. Best practices recomend that you wrap your content with the update panel, only in the areas you need to update. This way you won't generate much traffic.
In this case, the UpdatePanel, won't bind well with the button inside the content/page, and like so, it won't trigger the update on the update panel.

It is possible to use DataTables Column Filter Add-on with a Gridview

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.

Generate a table based on a selection from a dynamic drop down?

so I am learning ASP.NET currently and actually today is my second day.
So right now I am wanting to create a page where I have first a dynamically generated dropdown that selects just the first name from my database and table. This I have working
Next I have a gridview table that shows all the data from the database, currently I have hard coded a name so the page will not crash (there are 100000 rows of data)
Lastly when I post my code you will see a checkbox, that is just so when I click it the gridview will show up. I am just trying that out, because that was part of a lesson I learned today.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Test of First Database pull</h1>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" Text="Show Panel" OnCheckedChanged="checkbox1_CheckedChanged" />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="FirstName" DataValueField="FirstName" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ASP.NETConnectionString1 %>" ProviderName="<%$ ConnectionStrings:ASP.NETConnectionString1.ProviderName %>" SelectCommand="SELECT DISTINCT [FirstName] FROM [SampleData] ORDER BY 'FirstName' "></asp:SqlDataSource>
<br />
<br />
<asp:Panel ID="Panel1" runat="server" Visible="False" >
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="SSN" HeaderText="SSN" SortExpression="SSN" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="HomeStreet" HeaderText="HomeStreet" SortExpression="HomeStreet" />
<asp:BoundField DataField="HomeCity" HeaderText="HomeCity" SortExpression="HomeCity" />
<asp:BoundField DataField="HomeState" HeaderText="HomeState" SortExpression="HomeState" />
<asp:BoundField DataField="HomeZip" HeaderText="HomeZip" SortExpression="HomeZip" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="CompanyStreet" HeaderText="CompanyStreet" SortExpression="CompanyStreet" />
<asp:BoundField DataField="CompanyCity" HeaderText="CompanyCity" SortExpression="CompanyCity" />
<asp:BoundField DataField="CompanyState" HeaderText="CompanyState" SortExpression="CompanyState" />
<asp:BoundField DataField="CompanyZip" HeaderText="CompanyZip" SortExpression="CompanyZip" />
<asp:BoundField DataField="HomePhone" HeaderText="HomePhone" SortExpression="HomePhone" />
<asp:BoundField DataField="CompanyPhone" HeaderText="CompanyPhone" SortExpression="CompanyPhone" />
<asp:BoundField DataField="CellPhone" HeaderText="CellPhone" SortExpression="CellPhone" />
<asp:BoundField DataField="DateOfBirth" HeaderText="DateOfBirth" SortExpression="DateOfBirth" />
<asp:BoundField DataField="DateOfHire" HeaderText="DateOfHire" SortExpression="DateOfHire" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ASP.NETConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:ASP.NETConnectionString1.ProviderName %>"
SelectCommand="SELECT [SSN], [LastName], [FirstName], [HomeStreet], [HomeCity], [HomeState], [HomeZip], [CompanyName],
[CompanyStreet], [CompanyCity], [CompanyState], [CompanyZip], [HomePhone], [CompanyPhone], [CellPhone],
[DateOfBirth], [DateOfHire] FROM [SampleData] WHERE [FirstName] = 'Bob' "></asp:SqlDataSource>
</asp:Panel>
</div>
</form>
</body>
</html>
Here is my C# part where i call the session
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Demos_GridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = DropDownList1.SelectedValue;
Session["FName"] = name;
}
protected void checkbox1_CheckedChanged(object sender, EventArgs e)
{
Panel1.Visible = CheckBox1.Checked;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
As you see I called the session "I believe" I tried using this
<%:Session["user"]%>
within that sql query but it was saying I could not have the <%%> within the asp sql calling.
So if anyone could help me out that would be amazing.
Perhaps you should add the name of the user as a SqlParameter?
SqlDataSource1.SelectParameters.Add(new SqlParameter("#Name", name));
// Of course don't forget to edit your query: WHERE [FirstName] = #Name
Something as the above should work (note I haven't tested it).
Edit:
You could shorten this process even more by configuring your SqlDataSource to set the #Name parameter's value from a Control or Session.

Categories

Resources