DataTable must be set prior to using DataView - c#

Hi i did look at search result for " DataTable must be set prior to using DataView." but none of their solutions fixed my problem or pointed me in the right direction.
Were am i going wrong here, when i press a header to sort out the gridview table i just get an error and no sorting. The error is the same as my title for this post.
EDIT: Not sure if its relevant but i populate the gridview on page load from a MS SQL database
Mark-up
<asp:GridView ID="_propertyGridView" runat="server" CssClass="table table-hover table-striped" AutoGenerateColumns="false" AllowSorting="true" GridLines="None" OnRowCommand="PropertyRowCommand" Width="100%">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Ref" SortExpression="Id" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="PostCode" HeaderText="Post Code" SortExpression="PostCode" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="ContractsFinishedOn" HeaderText="Contract Signed On" SortExpression="ContractsFinishedOn" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Mobile" HeaderText="Mobile No." SortExpression="Mobile" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="LandLordEmail" HeaderText="Owners Email" SortExpression="LandLordEmail" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="MoveInDate" HeaderText="Move In Date" SortExpression="MoveInDate" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Status" SortExpression="Status1">
<ItemTemplate>
<asp:CheckBox ID="_tenantPaymentCheckBox" runat="server" Enabled="false" Checked='<%#Bind("TenantReceipt") %>' />
<asp:LinkButton ID="_tenantPaymentLink" Text="Send Tenant Receipt" CommandArgument='<%#Bind("Id") %>' CommandName="TenantEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the tenant, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status2">
<ItemTemplate>
<asp:CheckBox ID="_landlordInfoCheckBox" runat="server" Enabled="false" Checked='<%#Bind("LandlordInfo") %>' />
<asp:LinkButton ID="_landlordInfoLink" Text="Request Landlord Info" CommandArgument='<%#Bind("Id") %>' CommandName="LandlordInfoEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the landlord, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status3">
<ItemTemplate >
<asp:CheckBox ID="_landlordRentCheckBox" runat="server" Enabled="false" Checked='<%#Bind("LandlordReceipt") %>' />
<asp:LinkButton ID="_landlordRentLink" Text="Send Landlord Receipt" CommandArgument='<%#Bind("Id") %>' CommandName="LandlordEmail" runat="server" OnClientClick="javascript:return confirm('This will email & sms the landlord, please make sure its correct');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind
protected void _propertyGridView_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
SearchErrorLbl.Text = "error in such";
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
_propertyGridView.DataSource = DTSorting;
_propertyGridView.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
return (DataTable)ViewState["Sorting"];
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}

Seems to me that the problem is within SortGridView method. You try to use the very same DTSorting property you attempt to set as the table constructor parameter. If it is null at this point it will most definitely throw an exception. DataView needs an existing DataTable instance to work with.
I should also mention that the current implementation will likely create multiple DataTable instances that won't ever get disposed of. One thing for sure is that you aren't disposing of the DataView object you are creating so that you get your sorted table.
If I were you I would rethink how data should be bound. Storing a DataTable object in ViewState is bad practice. The full table will be serialized back and forth between the client and the server, resulting in performance loss.
I suggest you read about it here: View State Overview

Related

Edit gridview row asp.net without using commandfield

I would like to make a column editable in a gridview but without the edit column (the one with the keys update, cancel ...) due to space problems. I tried to recall the javascript functions related to those buttons in the onRowDataBound but onclick event is not taken. Here my code. Can anyone help me please?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex == GridView1.EditIndex) //GridView is in edit mode
{
//update or cancel buttons
LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
string updateScript = ClientScript.GetPostBackClientHyperlink(updateBtn, "");
Button1.Attributes["onclick"] = updateScript;
string cancelScript = string.Format("javascript:__doPostBack('{0}','Cancel${1}')", GridView1.ID, e.Row.RowIndex);
Button2.Attributes["onclick"] = cancelScript;
}
else //GridView is in read mode
{
//edit button
string editScript = string.Format("javascript:__doPostBack('{0}','Edit${1}')", GridView1.ID, e.Row.RowIndex);
e.Row.Attributes["onclick"] = editScript;
}
}
if (GridView1.EditIndex >= 0)
{
Button1.Enabled = true;
Button2.Enabled = true;
}
else
{
Button1.Enabled = false;
Button2.Enabled = false;
}
}
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" DataKeyNames="PKCOD" AllowPaging="True" PageSize="10"
CssClass="auto-style1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<%--
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<br />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" EnableClientScript="False" ErrorMessage="ErrorMessage" MaximumValue="999" MinimumValue="0" Type="Integer">Valori tra 0 e 999</asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
--%>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<ItemTemplate>
<asp:TextBox ID="textBoxQuantita" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" Type="Double" MinimumValue="0" MaximumValue="999" ControlToValidate="textBoxQuantita" runat="server"
ErrorMessage="Inserisci solo numeri compresi tra 0 e 999"></asp:RangeValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CODICE" HeaderText="CODICE" ReadOnly="True" SortExpression="CODICE" />
<asp:BoundField DataField="DESCRIZIONE" HeaderText="DESCRIZIONE" ReadOnly="True" SortExpression="DESCRIZIONE" />
<asp:BoundField DataField="CATEGORIA" HeaderText="CATEGORIA" ReadOnly="True" SortExpression="CATEGORIA" Visible="False" />
<asp:BoundField DataField="PKCOD" HeaderText="PKCOD" ReadOnly="True" SortExpression="PKCOD" InsertVisible="False" Visible="False" />
<asp:BoundField DataField="USERNAME" HeaderText="USERNAME" ReadOnly="True" SortExpression="USERNAME" Visible="False" />
<asp:BoundField DataField="USERID" HeaderText="USERID" ReadOnly="True" SortExpression="USERID" Visible="False" />
<asp:BoundField DataField="USERDT" HeaderText="USERDT" ReadOnly="True" SortExpression="USERDT" Visible="False" />
<asp:BoundField DataField="STATO" HeaderText="STATO" ReadOnly="True" SortExpression="STATO" Visible="False" />
</Columns>
</asp:GridView>

Accessing the value of a passed in argument to click event c#

I have a gridview defined like this...
<asp:GridView runat="server" id="gvProjectLineage"
ShowFooter="false"
DataKeyNames="projectLineageID"
AutoGenerateColumns="False"
AllowPaging="false"
AllowSorting="false"
RowStyle-CssClass="shade" CellSpacing="1"
AlternatingRowStyle-CssClass="unshade"
BorderColor="Transparent"
DataSourceID="gvProjectLineageDataSource"
Width="100%">
<HeaderStyle HorizontalAlign="Left" Font-Underline="true"></HeaderStyle>
<Columns>
<asp:BoundField ReadOnly="True"
HeaderText="Lineage ID"
InsertVisible="false"
DataField="projectLineageID"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="false">
</asp:BoundField>
<asp:BoundField ReadOnly="True"
HeaderText="Relationship type"
InsertVisible="false"
DataField="projectRelationshipType"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="true">
</asp:BoundField>
<asp:BoundField ReadOnly="True"
HeaderText="Related Project"
InsertVisible="false"
DataField="projectTitle"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="true">
</asp:BoundField>
<asp:TemplateField ShowHeader="False"
HeaderStyle-Font-Underline="false"
ItemStyle-HorizontalAlign="Left"
FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="btnDelete"
CommandArgument='<%# Eval("projectLineageID") %>'
CommandName="Delete"
runat="server">
<img style="border:none;"
src="/content/images/icon/deleteIcon.png"
title="Delete this lineage" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False"
HeaderStyle-Font-Underline="false"
ItemStyle-HorizontalAlign="Left"
FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="btnDeleteAll"
CommandArgument='<%# Eval("projectLineageID") %>'
runat="server"
OnClick="btnDeleteAll_Click" >
<img style="border:none;"
src="/content/images/icon/deleteIcon.png"
title="Delete this lineage AND it's reciprocal lineage" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>There are currently no relationships identified for this S&T project.</EmptyDataTemplate>
</asp:GridView>
The first "delete" button calls a simple delete query and it works fine to delete the selected row from the table. However, when I call the 2nd delete button ("DeleteAll"), I want to use the [projectLineageID] to find the related lineage records for a project and delete them all at once.
When I call the 2nd delete function "onclick" as follows, I get nothing in column [0].
protected void btnDeleteAll_Click(object sender, EventArgs e)
{
//Delete lineage and reciprocal lineage for relationship types 1 (Transitioned from) and 2 (Transitioned to)
util u = new util();
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string strRelID = grdrow.Cells[0].Text;
int intRelID = System.Convert.ToInt32(grdrow.Cells[0].Text);
string relType = grdrow.Cells[1].Text;
string relProj = grdrow.Cells[2].Text;
Response.Write ("Deleting relationship between " + projectID + " and the project in column 3 " + relID + " " + relType + " " + relProj + " :");
}
How do I get the projectLineageID to pass it to the query?
And, why can't I display it? Even if I try to "convert" it, I get an error telling me the "Input string was not in a correct format."
Thanks,
Bob

How to disable LinkButton within GridViewclick from Client Side using JavaScript?

I have a GridView, In one column I have LinkButton control. I want to disable click from client side for certain condition on this column. Means for some rows it will not be possible for User to call onclick event and for some rows it is possible.
I want to achieve this from client side using javascript.
Or When User clicks on link, It will notify the User that this action can't be completed for this row.
<asp:GridView Width="100%" ShowHeader="true" ViewStateMode="Enabled" GridLines="Both" CellPadding="10" CellSpacing="5" ID="GridViewMultiplePOSAssociationId" runat="server" AllowSorting="false" AutoGenerateColumns="false" OnRowCommand="RewardGridMultiD_RowCommand"
AllowPaging="true" PageSize="8" OnRowDataBound="grdViewCustomers_OnRowDataBound" PagerSettings-Position="Top" PagerSettings-Mode="NumericFirstLast" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last" DataKeyNames="POS Id">
<RowStyle CssClass="table_inner_text" BackColor="WhiteSmoke" BorderColor="CornflowerBlue" Wrap="true" ForeColor="Black" Height="30px" />
<HeaderStyle CssClass="table_head_text" />
<Columns>
<asp:TemplateField ItemStyle-Width="80px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval(" POS Id ") %>');">
<img alt="Details" id="imgdiv<%# Eval("POS Id") %>" src="images/plus.png" />
</a>
<div id="div<%# Eval(" POS Id ") %>" style="display: none;">
<asp:GridView ID="grdViewOrdersOfCustomer" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<RowStyle CssClass="table_inner_text" BackColor="SkyBlue" BorderColor="Black" Wrap="true" ForeColor="White" Height="30px" />
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="RULE FILE NAME" HeaderText="RULE FILE NAME" />
<asp:BoundField ItemStyle-Width="150px" DataField="RULE ID" HeaderText="RULE ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="RULE TYPE ID" HeaderText="RULE TYPE ID" />
<asp:BoundField ItemStyle-Width="150px" DataField="START TIME" HeaderText="START TIME" />
<asp:BoundField ItemStyle-Width="150px" DataField="EXPIRY TIME" HeaderText="EXPIRY TIME" />
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="Row Number">
<ItemTemplate>
<asp:Label ID="LabelRowNumberId" runat="server" Text='<%#Eval("Row Number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="POS Id">
<ItemTemplate>
<asp:Label ID="LabelPOSID" runat="server" Text='<%#Eval("POS Id") %>'></asp:Label>
<%-- <asp:LinkButton ID="LinkbtnPOSId" CommandArgument='<%#Eval("POS Id") %>' CommandName="ClickPOS" Text='<%#Eval("POS Id") %>' runat="server" CausesValidation="false"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="HyperLinkAssociate" CommandArgument='<%#Eval("POS Id") %>' CommandName="Associate" Text="Associate" runat="server" OnClientClick="return OnClientClickAssociateRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>/
<asp:LinkButton ID="HyperLinkReplace" CommandArgument='<%#Eval("POS Id") %>' CommandName="Replace" Text="Replace" runat="server" OnClientClick="return OnClientClickReplaceRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Status">
<ItemTemplate>
<asp:Label runat="server" ID="LabelStatusPendingPOSId" Text='<%#Eval("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In GridViewMultiplePOSAssociationId there is one column "Status" which has label LabelStatusPendingPOSId, LabelStatusPendingPOSId text is set Applied, Not Applied at the time of Binding. For Rows which has Status Applied, User should not be able to click on LinkButton Associate/Replace else He is allowed to click.
use this code OnRowDataBound for Your Grid
protected void grdViewCustomers_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType==DataControlRowType.DataRow)
{
LinkButton LinkbtnPOSId=(LinkButton)e.Row.FindControl("LinkbtnPOSId");
Label LabelStatusPendingPOSId = (Label)e.Row.FindControl("LabelStatusPendingPOSId");
Boolean boolStatus = LabelStatusPendingPOSId.Text == "Applied" ? true : false;
//LinkbtnPOSId.Attributes.Add("onclick", "function CheckStatus('" + boolStatus.ToString() + "')");
LinkbtnPOSId.Enabled = boolStatus;
}
}
Try this..
You can loop through the Gridview and make the particular control disable...
I am writing the code in javascript pageload function...
function PageLoad(sender, args)
{
for (var i = 0; i <= RowCount; i++)
{
document.getElementById('Gridview1_HyperLinkAssociate_' + i.toString() + '').disabled = true;
}
}
Set RowCount as the number of rows of the Gridview...

Why this code doesn't output anything to label?

<asp:GridView runat="server" ID="gridUserAccounts" SkinID="gridviewSkin" PageSize="5">
<Columns>
<asp:BoundField HeaderText="User Name" DataField="UserName" />
<asp:BoundField HeaderText="Email" SortExpression="Email" DataField="Email" />
<asp:BoundField HeaderText="Last Login Date" SortExpression="LastLoginDate" DataField="LastLoginDate" />
<asp:BoundField HeaderText="Last Activity Date" SortExpression="LastActivityDate" DataField="LastActivityDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# string.Format("manage-user-detail.aspx?UserName={0}", Eval("UserName")) %>' ID="linkNavigate" Text="View Detail" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind for this is
if (!Page.IsPostBack)
{
gridUserAccounts.DataSource = Membership.GetAllUsers();
gridUserAccounts.DataBind();
}
Now, at 'manage-user-detail.aspx' page i am catching the query string but it doen't work like this
if (!IsPostBack)
{
string userKey1 = Request.QueryString["UserName"];
Guid UserID = new Guid(Membership.GetUser(userKey1).ProviderUserKey.ToString());
//Guid userKey = new Guid(userKey1);
MembershipUser mu = Membership.GetUser(UserID);
//string userName = mu.UserName;
lblKey.Text = mu.UserName;
}
Nothing is showing up in label. Why?
I solve the problem with following code
string userName = Membership.GetUser(Request.QueryString["UserName"].ToString()).UserName;
statusLabel.Text = userName;
From my experience the only way to get the querystring is like so:
Request.QueryString.Item("UserName");
I see that in your code you left out Item.

Value from row with DropDownList on DropDownList Index Changed Event

Code:
<asp:GridView ID="gv_Recruit" AutoGenerateColumns="False" Width="100%"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlCities" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl_selected">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Recruiter" DataField="Recruiter" />
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
Code Behind:
protected void ddl_selected(object sender, EventArgs e)
{
string _dd_value = ((DropDownList)sender).SelectedValue;
string trying_to_get = gv_Recruit.Rows[???].Cells[0].Text.ToString();
string also_tried = gv_Recruit.SelectedRow.Cells[0].Text.ToString();
}
Basically what I'm trying to do is get the key value from the first row when the drop down is changed so I can perform an update ???
Can't figure this out.
Thanks in advance for the help...
Try
GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;
string trying_to_get = string.Empty;
if (gRow != null)
{
trying_to_get = gRow.Cells[0].Text;
}

Categories

Resources