How to refresh a GridView/LINQ data source from textbox onchange event - asp.net

I've been having troubles getting my textbox to refresh a GridView from the onchange event.
The GridView is linked up to a LINQ data source and the LINQ data source has a Where Parameter UserId that it gets from the textbox... Here's the code:
<asp:Label ID="label_UserId" runat="server" Text="Search by User Id: "></asp:Label>
<asp:TextBox ID="textbox_UserId" Text="12" runat="server"
ontextchanged="textbox_UserId_TextChanged"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="UserID" DataSourceID="LINQUserSource"
EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True"
SortExpression="UserID" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LINQUserSource" runat="server"
ContextTypeName="DotNetNuke.Modules.Report.UsersDataContext"
Select="new (UserID, Username, FirstName, LastName, Email)" Where="UserId = #UserId"
TableName="Users">
<WhereParameters>
<asp:ControlParameter
Name="UserId"
DefaultValue="0"
ControlID="textbox_UserId"
Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
So far I have nothing for the backend code. Since I set the textbox to be 12 by default, the GridView loads with the record of UserId 12, but now I want the GridView to reload if I change the number in the textbox. Any ideas?

First add the AutoPostBack property to your TextBox:
<asp:TextBox ID="textbox_UserId" Text="12" runat="server"
AutoPostBack="true" ontextchanged="textbox_UserId_TextChanged"/>
Then, put this in your code behind:
protected void textbox_UserId_TextChanged(object sender, EventArgs e)
{
GridView1.DataBind();
}

Just call
GridView1.DataBind();
after you enter new value.

OleDbCommand cmd = new OleDbCommand("update ESInfo1 set OrdTime='" + td.ToString() + "', SSO2='" + DropSupportOfficer.Text + "', Orderby='" + Txthst.Text + "' where Sln=" + Txtsln.Text + "", con);
cmd.ExecuteNonQuery();
GridView1.DataBind();
cmd.Dispose()
but no row present in gridview

create a datatable method and return
GridView1.DataSource = method(); GridView1.DataBind();

Related

How do i know which Buttons are triggered to perform specific task in Gridview

I have 2 buttons, one is called "Accept", which is used for updating of database while another is called "View", which is used for Redirecting. However, in GridView's SelectedIndexChanged, i wasnt able to Validate which buttons were click
so I have tried Using RowCommand for the "View" button and SelectedIndexChanged for "Accept" button. But RowCommand is triggering the "Accept" button in the SelectedIndexChanged event handler.
<asp:GridView ID="QgridView" AutoGenerateColumns="False"
CssClass="table table-bordered" AllowPaging="True" PageSize="6"
BackColor="White" BorderColor="Black" BorderStyle="Solid"
ForeColor="Black" GridLines="None" runat="server"
OnRowCommand="QgridView_RowCommand"
OnSelectedIndexChanged="QgridView_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="No">
<ItemTemplate>
<span>
<%#Container.DataItemIndex + 1%>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="Image" DataImageUrlField="coverimg" >
<ControlStyle CssClass="coverimage"/>
<ItemStyle HorizontalAlign="Center" />
</asp:ImageField>
<asp:BoundField HeaderText="Buyer" DataField="buyer" />
<asp:BoundField HeaderText="Item" DataField="item" />
<asp:BoundField HeaderText="Price offered" DataField="price" />
<asp:buttonfield buttontype="Button"
commandname="Accept"
text="Accept"/>
<asp:BoundField DataField="quoteid" HeaderText="quoteid" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="id" HeaderText="id" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="rtype" HeaderText="rtype" ItemStyle-
CssClass="hiddencol" HeaderStyle- CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="seller" HeaderText="seller" ItemStyle-
CssClass="hiddencol" HeaderStyle-CssClass="hiddencol">
<HeaderStyle CssClass="hiddencol"></HeaderStyle>
<ItemStyle CssClass="hiddencol"></ItemStyle>
</asp:BoundField>
<asp:buttonfield buttontype="Button"
commandname="View"
text="View"/>
</Columns>
</asp:GridView>
// Behind COde page
protected void QgridView_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = QgridView.SelectedRow;
string seller = row.Cells[10].Text;
string item = row.Cells[4].Text;
string type = row.Cells[9].Text;
int id = Convert.ToInt32(row.Cells[8].Text);
int quoteid = Convert.ToInt32(row.Cells[7].Text);
productDAO productdao = new productDAO();
productdao.GridPush(quoteid, id)
}
protected void QgridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
Response.Redirect("ListingItems.aspx");
}
}
I want the "Accept" BUtton to perform the updating of database while the "View button to perform Response.Redirect. However, RowCommand does not fire and instead, it triggers the "Accept" button in SelectedIndexChanged. May i know how can perform the different task for each button?
[Gettting row data from GridView]
protected void QgridView_RowCommand(object sender,
GridViewCommandEventArgs e)
{
System.Diagnostics.Debug.WriteLine("onrowcommand");
if (e.CommandName == "View")
{
System.Diagnostics.Debug.WriteLine("ButtonView is clicked");
Response.Redirect("ListingItems.aspx");
}
else if (e.CommandName == "Accept")
{
System.Diagnostics.Debug.WriteLine("buttonAccept is clicked");
productDAO productdao = new productDAO();
//GridViewRow row = QgridView.SelectedRow;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = QgridView.Rows[index];
string id = row.Cells[8].Text; //Returns me nothing
}
else
{
System.Diagnostics.Debug.WriteLine("no command name");
}
}
I think you are no need to check the rowcommand or onselected Index change event you can directly set button on click event. if you are using the inside your Gridview, then you should be able to register an event in your button code as:
<asp:Button runat="server" OnClick="YourclickEvent" />
For more details on event you should read this: https://www.codeproject.com/Articles/50540/GridView-Event-Handling
One Addition: if using row command then identify each button with command name and you can perform your task easily.
According to your code SelectedIndexChanged should be never fired (no select command).
RowCommand handler always fire first (before more specific handlers).
Look at sample working code.
.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID"
DataSourceID="sqlCategory"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" SortExpression="CategoryName" />
<asp:ButtonField ButtonType="Button" CommandName="Accept" HeaderText="Accept" ShowHeader="True" Text="Accept" />
<asp:ButtonField ButtonType="Button" CommandName="View" HeaderText="View" ShowHeader="True" Text="View" />
<%-- Use HyperLinkField instead of ButtonField --%>
<asp:HyperLinkField DataNavigateUrlFields="CategoryID" DataNavigateUrlFormatString="category.aspx?categoryid={0}" DataTextField="CategoryName" DataTextFormatString="View {0}" HeaderText="Direct View" />
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
<%-- Data from NorthWind learning DB --%>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnection %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
UpdateCommand="update categories set categoryName=#CategoryName where CategoryID=#CategoryID">
<UpdateParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
<asp:Parameter Name="CategoryName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
.aspx.cs
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Trace.Write("GridView1_SelectedIndexChanged");// fired by "select" command after RowCommand finished
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Trace.Write("GridView1_RowCommand");
//
if (e.CommandName == "Accept")
{
var categoryId = (int)GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;//e.CommandArgument is display index
Trace.Write(e.CommandName + ": " + e.CommandArgument + " : " + categoryId.ToString());
}
else if (e.CommandName == "View")
{
Trace.Write("View " + e.CommandArgument);
}
}

Show record in gridview based on dropdown list, fromdate and enddate entered in textbox

I need to show my data in a gridview based on my dropdown list, fromdate and todate when data is entered in the textbox. How can I do that? What I have done till now is I created two pages. In first page I have a dropdown list and a form. When I select value from drop-down list the form for the selected value appears and user can enter details in it and submits that form. After submitting the data store in the database. In second page I have a grid view where stored value can be seen, dropdown list, from date and to date textbox now what I want is to show the records in the gridview based on my dropdown selection, fromdate and todate.
Code for second form:
<asp:DropDownList ID="ddlPortal" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlPortal_SelectedIndexChanged">
<asp:ListItem>TRAVELONG</asp:ListItem>
<asp:ListItem>ONETRAVEL</asp:ListItem>
<asp:ListItem>.UK-BSP</asp:ListItem>
<asp:ListItem>.CA-YYZ</asp:ListItem>
<asp:ListItem>.CA-YVR</asp:ListItem>
<asp:ListItem>Partial MCO Refund</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lbFrom" Text="From" runat="server" /> <asp:TextBox ID="tbFrom" runat="server" />
<asp:Label ID="lblto" Text="To" runat="server" /> <asp:TextBox ID="tbTo" runat="server" />
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click" />
Gridview details:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Query">
<itemtemplate>
<asp:LinkButton CommandName="cmdBind" runat="server" Text='<%#Eval("ID")%>' ID="ID" ToolTip='<%#Eval("ID")%>'>LinkButton
</asp:LinkButton>
</itemtemplate>
</asp:TemplateField>
<asp:BoundField DataField="Portal" HeaderText="Portal" />
<asp:BoundField DataField="TID" HeaderText="TID" />
<asp:BoundField DataField="PNR" HeaderText="PNR" />
<asp:BoundField DataField="TicketNumber" HeaderText="Ticket Number" />
<asp:BoundField DataField="ESACCode" HeaderText="ESACCode" />
<asp:BoundField DataField="WaiverCode" HeaderText="WaiverCode" />
<asp:BoundField DataField="Remarks" HeaderText="Remarks" />
<asp:BoundField DataField="UnusedTicketAmount" HeaderText="UnusedTicketAmount" />
<asp:BoundField DataField="ddlUnusedAmount" HeaderText="ddlUnusedAmount" />
<asp:BoundField DataField="AirlinePenality" HeaderText="AirlinePenality" />
<asp:BoundField DataField="ddlAirlinePenality" HeaderText="ddlAirlinePenality" />
<asp:BoundField DataField="NetRefundProcess" HeaderText="NetRefundProcess" />
<asp:BoundField DataField="ddlNetRefundProcess" HeaderText="ddlNetRefundProcess" />
<asp:BoundField DataField="RefundableCommission" HeaderText="RefundableCommission" />
<asp:BoundField DataField="ddlRefundableCommission" HeaderText="ddlRefundableCommission" />
<asp:BoundField DataField="CouponRefunded" HeaderText="CouponRefunded" />
<asp:BoundField DataField="RefundType" HeaderText="RefundType" />
</Columns>
I want to write code on click event of button but I don't know how. Can you help me on this?
.cs file:
protected void btnSearch_Click(object sender, EventArgs e)
{
}
If you are using DataTable for binding your GridView then, you can filter the data & bind your GridView again.
You can use: DataView.RowFilter Property for filtering data.
Eg.:
DataTable dt= GetData();
DataView dv = dt.DefaultView;
dv.RowFilter = "Portal= '" + ddlPortal.SelectedValue.Trim() + "'"
GridView1.DataSource=dv;
GridView1.DataBind();
Also, you can use LINQ to filter data:
DataTable dt= GetData();
EnumerableRowCollection<DataRow> query =
from row in dt.AsEnumerable()
where row.Field<String>("Portal") == ddlPortal.SelectedValue.Trim()
select row;
DataView dv = query.AsDataView();
GridView1.DataSource=dv;
GridView1.DataBind();

LinqDataSource_Selecting does not work

I have used a gridview and linqdatasourse , the gridview will be fill by a linq-stored procedure after clicking a search button.
I did it like below but my grid view is empty.
It seems LinqDataSource2_Selecting does not work.
Please help what is the problem?
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
_DataContext = new EDMSDataContext();
var subjectFilter = e.WhereParameters["Subject"];
var query = _DataContext.spQuickSearchDoc(subjectFilter);
e.Result = query;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
this.GridViewDocuments_Search.DataBind();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
#Searchtext varchar(50)=null
AS
select DocId,DocumentNo,Title,Unit
from tblDocuments
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or Unit like '%'+#SearchText + '%'
Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo" SortExpression="DocumentNo" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting">
<WhereParameters>
<asp:ControlParameter Name="Subject"
ControlID="txtSearchKeywords"
PropertyName="Text"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
You need to add DataSourceID to the GridView, as in:
<asp:GridView ID="GridViewDocuments_Search" runat="server"
. . DataSourceID="LinqDataSource2">
Since it's not set, the GridView is being bound to NULL.

Setting the hyperlink value to a datagrid in asp.net

I have a datagrid that is being populated by DirectoryInfo. The columns are Name, Date & Size. The Name value is a hyperlink.
The hyperlink url should be: "javascript:openFile('" & sFileName & "');"
My code is:
Dim sFilePath As String = strDirectoryPath + OrderDocName
Dim dirInfo As New DirectoryInfo(strDirectoryPath)
dgOrderDocList.DataSource = dirInfo.GetFiles("*.*")
dgOrderDocList.DataBind()
<asp:DataGrid runat="server" id="dgOrderDocList"
AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#eeeeee"
HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Size="10pt" HeaderStyle-Font-Bold="True">
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name"
HeaderText="File Name" ItemStyle-Font-Size="Small" />
<asp:BoundColumn DataField="Length" HeaderText="File Size"
ItemStyle-HorizontalAlign="Right"
DataFormatString="{0:#,### bytes}" ItemStyle-Font-Size="Small"/>
<asp:BoundColumn DataField="LastWriteTime" HeaderText="Date"
ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" ItemStyle-Font-Size="Small"/>
</Columns>
</asp:DataGrid>
Have you tried creating an TemplateField? Then you can overload the OnRowDataBound event find the anchor control and use server side logic to create your anchor. Something like this..
<columns>
<asp:TemplateField>
<asp:ItemTemplate>
<asp:HyperLink id="hyperlink1" runat="server" />
</asp:ItemTemplate>
</asp:TemplateField>
</columns>
gv_OnRowDataBound(Object sender, GridViewRowEventArgs e){
GridViewRow row = this.gv.Rows[e.index];
var hyperLink = row.findControl("hyperlink1");
\\Set target and NavigateUrl properties
}

ImageButton and GridView problem - invalid postback

I currently have a Gridview which uses a ButtonField of type image and this works.
However I want to be able to use the ConfirmButtonExtender that is part of the AjaxControlToolkit which cannot operate on a Buttonfield so I decided to place an ImageButton inside a TemplateField however whenever I click the button I recieve an Invalid postback or callback argument error.
Any advice/suggestions would be greatly appreciated. Thank you.
New template field
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" ImageUrl="~/Images/cross.png" CommandArgument='<% Eval("soid") %>' CommandName="deleteSO" AlternateText="Delete" OnClick="ibtnDelete_Click" ToolTip="Delete the selected standing order" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Existing GridView
<asp:GridView ID="gvStandingOrders" runat="server" DataKeyNames="soid" OnRowCommand="gvStandingOrders_RowCommand">
<Columns>
<asp:ButtonField ButtonType="Image" CommandName="editSO" ImageUrl="~/Images/page_white_paintbrush.png" Text="Edit" />
<asp:ButtonField ButtonType="Image" CommandName="deleteSO" ImageUrl="~/Images/cross.png" Text="Delete" />
<asp:BoundField DataField="Prefix" HeaderText="Prefix" />
<asp:BoundField DataField="PhoneNumber" HeaderText="Phone Number" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Amount" DataFormatString="{0:C}" HeaderText="Customer Charge" />
<asp:BoundField DataField="SOCost" DataFormatString="{0:C}" HeaderText="Bureau Buy Price" />
<asp:BoundField DataField="UnitPrice" DataFormatString="{0:C}" HeaderText="TMS Buy Price" />
<asp:BoundField DataField="Frequency" HeaderText="Frequency" />
<asp:BoundField DataField="StartDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Start Date" />
<asp:BoundField DataField="LastInvoiceDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Last Invoice Date" />
<asp:BoundField DataField="NextInvoiceDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Next Invoice Date" />
<asp:BoundField DataField="EndDate" DataFormatString="{0:dd/MM/yyyy}" HeaderText="End Date" />
<asp:BoundField DataField="soid" HeaderText="SO ID" />
</Columns>
</asp:GridView>
Code behind
protected void gvStandingOrders_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("editSO"))
{
Session["SOID"] = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
Response.Redirect("/Main/ClientMaintenance/StandingOrders/EditStandingOrder.aspx", true);
}
else if (e.CommandName.Equals("deleteSO"))
{
int soid = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
// Header
int provisionID = Provisioning.GenerateHeader("SO", "provisioning_standingorder");
// Create Details
GlobFunctions.UpdateStoredProc("InsertStandingOrderHeader", GlobVar.ObjConnClick, new SqlParameter[]
{
new SqlParameter("#ProvisionID", provisionID),
new SqlParameter("#Client_Action", "D"),
new SqlParameter("#SOID", soid)
});
// Audit
GlobFunctions.AddToAudit(String.Format("Removing standing order : {0}", soid), Session["CustomerCode"].ToString());
}
}
protected void ibtnDelete_Click(object sender, ImageClickEventArgs e)
{
//select the row
ImageButton imageButton = (ImageButton)sender;
TableCell tableCell = (TableCell)imageButton.Parent;
GridViewRow row = (GridViewRow)tableCell.Parent;
int soid = Convert.ToInt32(gvStandingOrders.DataKeys[Convert.ToInt32(row.RowIndex)].Value);
// Header
int provisionID = Provisioning.GenerateHeader("SO", "provisioning_standingorder");
// Create Details
GlobFunctions.UpdateStoredProc("CLICK10_InsertStandingOrderHeader", GlobVar.ObjConnClick, new SqlParameter[]
{
new SqlParameter("#ProvisionID", provisionID),
new SqlParameter("#Client_Action", "D"),
new SqlParameter("#SOID", soid)
});
// Audit
GlobFunctions.AddToAudit(String.Format("Removing standing order : {0}", soid), Session["CustomerCode"].ToString());
}
CommandArgument='<% Eval("soid") %>'
should be
CommandArgument='<%# Eval("soid") %>'
Note the "<%# "

Resources