DataBind GridView OnKeyUp/Down - asp.net

I have a gridview that will display customer information. I want it to update the results as the user types first and/or last name into the textboxes. Basically, to databind the gridview to it's datasource with the updated characters from the textboxes as the user types.
CODE EDITED:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Process.aspx.cs" Inherits="Reservations.WebForm3" %>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>Processing...</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="firstname" runat ="server" class="inputLarge" ontextchanged="firstname_TextChanged" />
<asp:TextBox ID="lastname" runat="server" class="inputLarge" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="457px">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="CustID" HeaderText="Cust ID">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="FirstName" HeaderText="First Name">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="LastName" HeaderText="Last Name">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="City" HeaderText="City">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts></Scripts>
</asp:ScriptManager>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="firstname" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
protected void firstname_TextChanged(object sender, EventArgs e)
{
InventoryAppSoapClient inst = new InventoryAppSoapClient();
DataSet ds = inst.getCustomer(firstname.Text, "none");
GridView1.DataSource = ds;
GridView1.DataBind();
}
Everything works except the TextChanged event only first the first time. If I go back and change the text and tab off, nothing happens.

Have you tried adding an event handler for the OnTextChanged event of your text box.
Inside you could force the databind like so
Private void firstName_OnTextChanged(object sender, EventArgs e)
{
//Your datasource and parameters are already defined on the front end so there is no
//setup required
existing.DataBind();
}
Same goes for your text box lastName
Private void lastName_OnTextChanged(object sender, EventArgs e)
{
//Your datasource and parameters are already defined on the front end so there is no
//setup required
existing.DataBind();
}
And don't forget to add the methods to the OnTextChange attribute for each textbox in the front end. Like so.
<asp:TextBox ID="firstname" OnTextChanged="firstName_OnTextChanged" runat ="server" class="inputLarge"/>
<asp:TextBox ID="lastname" OnTextChanged="lastName_OnTextChanged" runat="server" class="inputLarge" />
Also, if you embed this code in an update Panel and use the AJAX control toolkit (free) the grid will update seamlessly. Otherwise it won't be pretty if you use classic asp techniques. The page will keep posting back every time you press a key. It will get annoying.

Related

Linkbutton's event in GridView not firing its event on 2nd Time

Seems to be a weird problem but my Linkbutton which is in GridView is not firing its event on 2nd Time.
In Detail:
I have a GridView which has linkButton in it which is firing an event. This event is fired perfectly on first time but not working(not posting back) when i click it on 2nd time.
<asp:GridView ID="dg1" runat="server" OnSorting="dg1_Sorting" OnRowCreated="GridViewSortImages"
SkinID="grid" Width="100%" Font-Underline="false" HeaderStyle-Font-Underline="false"
OnRowCommand="dg1_RowCommand" AllowPaging="True" HeaderStyle-HorizontalAlign="Left"
OnRowDataBound="dg1_RowDataBound" ShowFooter="true">
<Columns>
<asp:TemplateField ItemStyle-Width="15px">
<ItemTemplate>
<asp:ImageButton ID="imgbtndel" runat="server" OnClick="imgbtndel_Click" ImageUrl="~/css/Images/delete.gif"
OnClientClick="return confirm('Do you want to Delete')"></asp:ImageButton>
</ItemTemplate>
<ItemStyle Width="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Account Type ID" SortExpression="ID" ItemStyle-Width="60px"
HeaderStyle-Font-Underline="false">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnno" runat="server" ForeColor="#123B61" Text='<%#Eval("ID") %>'
OnClick="lnkbtnno_Click"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle Font-Underline="False" />
<ItemStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="200px" />
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void lnkbtnno_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
txtaccid.Text = lnkbtn.Text;
Label lblDesc = lnkbtn.FindControl("lblDesc") as Label;
txtdesc.Text = lblDesc.Text;
}
your linkbutton not firing events for second time.Because some other events got fired in second time instead of your linkbutton. So in events stack linkbutton events got disabled. Checkit out whether you added dynamic control are firing or not. Make use developer tools like firebug(F12)

why my bound field not working inside grid view with update pane?

i have a grid view inside update panel with multiple bound fields the last two bound field as shown in image when click show another grid view without post back but download not working except i set EnablePartialRendering="false" of script-manager
but in this case updatepanel not working to show bound field
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<contenttemplate>
<div id="DivImages" runat="server" visible="false" class="block rnd">
<div class="title2">الأحكـــــــــــام</div>
<div class="content2">
<asp:gridview ID="GvImages" runat="server" PagerStyle-CssClass="pages" AllowPaging="True"
AutoGenerateColumns="False" CellSpacing="-1" Width="100%" DataKeyNames="DocCode,IssuesID"
CssClass="dataGrid" OnPageIndexChanging="GvImages_PageIndexChanging" GridLines="None"
PageSize="20" OnRowCommand="GvImages_RowCommand"
OnSelectedIndexChanging="GvImages_SelectedIndexChanging">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="رقم السجــل">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocCode" HeaderText="رقم الحكم/ القرار" SortExpression="DocCode" />
<asp:BoundField DataField="IssuesNum" HeaderText="كود القضيه"
SortExpression="IssuesNum" />
<asp:BoundField DataField="TypeName" HeaderText="نوع القضيه"
SortExpression="TypeName" />
<asp:BoundField DataField="Year" HeaderText="السنه"
SortExpression="Year" />
<asp:BoundField DataField="Area" HeaderText="المنطقه"
SortExpression="Area" />
<asp:BoundField DataField="DocTypeName" HeaderText="تصنيــف المستند" SortExpression="DocTypeName" />
<asp:BoundField DataField="Name" HeaderText="نوع المستند"
SortExpression="Name" />
<asp:TemplateField HeaderText="حذف">
<ItemTemplate>
<asp:LinkButton ID="cmd_DeleteRow" CommandName="DeleteRow" CssClass="delete" ToolTip="حذف" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" runat="server" OnClientClick="return confirmDeleteRow()" />
</ItemTemplate>
<HeaderStyle Width="125px" />
</asp:TemplateField>
<asp:CommandField SelectText="عرض" HeaderText="عرض" ShowHeader="True" ShowSelectButton="True">
<HeaderStyle HorizontalAlign="Right" />
</asp:CommandField>
<asp:TemplateField HeaderText="تحميل">
<ItemTemplate>
<asp:LinkButton ID="DownLoad" CommandName="DownLoad" Text="تحميل" ToolTip="تحميل" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" runat="server" />
</ItemTemplate>
<HeaderStyle Width="125px" />
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px" />
<PagerStyle CssClass="pages" Wrap="false" />
</asp:gridview>
</div>
</div>
</contenttemplate>
<Triggers>
in button search i bind my grid
like in this code
protected void ShowDoc(string sCondition)
{
//declare connection by pass connection string from web.config
SqlConnection sqlcon = new SqlConnection
(ConfigurationManager.ConnectionStrings["SystemConn"].ConnectionString);
//declare sql statment as astring variable
if (Session["Image"] != null)
{
Session.Remove("Image");
}
try
{
SqlStatment = string.Format("select distinct IssuesNum,DocType,DocTypeSub,DocCode,DocTypeName,Name,IssuesID,TypeID,TypeName,Area,IssuesNumSplited,Year from [View_ImagesSearch] Where {0} Order By [IssuesNumSplited] ASC", sCondition);
//create asql command and pass for it the connection string and sql statment
SqlCommand sqlcom = new SqlCommand(SqlStatment, sqlcon);
//create data adaptor to bring data from database
SqlDataAdapter sad = new SqlDataAdapter(sqlcom);
// declare dataset to store data from data base in it
DataSet ds = new DataSet();
//fill data set with data adabter that contain data from database
sad.Fill(ds);
lblDocCount2.Text = ds.Tables[0].Rows.Count.ToString();
Session["Image"] = ds;
GvImages.DataSource = ds;
GvImages.DataBind();
}
catch (Exception ex)
{
par_ErrorMessage.Visible = true;
par_ErrorMessage.InnerText = ex.Message;
}
}
when i click command called عرض updatepanel work to show another gridview
but when iclick item template download not workink fine untill i set EnablePartialRendering="False"
Make sure you are calling Update on the UpdatePanel after you call DataBind on the GridView:
GridView.DataBind();
UpdatePanel.Update();
See this for other possible solutions.

button gridview in UpdatePanel

i use gridview and UpdatePanel in asp.net.
<asp:UpdatePanel ID="upSubject" runat="server">
<ContentTemplate>
<div class="c_box" style="height: auto; text-align: center; margin-top: 10px; width:565px; padding-right:140px;">
<asp:GridView ID="gvSubject" runat="server" AutoGenerateColumns="False"
SkinID="gvSubject" ShowHeader="true" ShowHeaderWhenEmpty="true"
onrowcommand="gvSubject_RowCommand">
<Columns>
<asp:BoundField DataField="lblCounter" HeaderText="Number" ReadOnly="True" HeaderStyle-Font-Bold="false" ItemStyle-Width="60px"></asp:BoundField>
<asp:BoundField DataField="lblSubject" HeaderText="Tiltle" ReadOnly="True" HeaderStyle-Font-Bold="false" ItemStyle-Width="300px" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center" HeaderStyle-Font-Bold="false" ItemStyle-Width="60px">
<ItemTemplate>
<asp:ImageButton ID="dltSubject" runat="server" CommandName="remove" CommandArgument="lblCounter" ValidationGroup="Subject" OnClientClick="return confirm('Delete?')" ImageUrl="~/Style/Pic/pic_delete_small.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#000000" />
<EmptyDataRowStyle BackColor="#00ff00" />
<EmptyDataTemplate>
Not item...
</EmptyDataTemplate>
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:asyncpostbacktrigger controlid="gvSubject" eventname="RowCommand" />
</Triggers>
</asp:UpdatePanel>
or
<asp:asyncpostbacktrigger controlid="dltSubject" eventname="Click" />
.
protected void gvSubject_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "remove")
{
DataTable _dt = (DataTable)Session["Subject"];
_dt.Rows[int.Parse(e.CommandArgument.ToString())].Delete();
gvSubject.DataSource = _dt;
gvSubject.DataBind();
Session["Subject"] = _dt;
}
}
but not work UpdatePanel. please help me for work button gridview in UpdatePanel.
i want work ImageButton in gridview and UpdatePanel.
You dont have to use Triggers for the RowCommand. Also remove rowcommand if you dont want to use besides this button click.
Please specify OnCommand=dtlSubject_Click
I have used here "Number" as commandargument thinking that it is your unique id needed to delete the record.
You need to specify unique column for deletion in commandargument.
<asp:ImageButton ID="dltSubject" runat="server"
CommandArgument='<%#DataBinder.Eval(Container.DataItem, "Number")%>'
ValidationGroup="Subject" OnCommand="dtlSubject_Click"
OnClientClick="return confirm('Delete?')" ImageUrl="~/Style/Pic/pic_delete_small.png" />
And on server side write down following code :
protected void dtlSubject_Click(object sender, CommandEventArgs e)
{
string uniqueid= e.CommandArgument.ToString();
//call your procedure here to delete your item.
}

Could not Update Text box control values

I am really frustrated to find a solution for my scenario. I have two gird when First grid is used show the shop information and the second grid is used to edit the offers related to the shop information. When the users edit the second grid i will just update the text box values related to the grid selection row. in my code behind file i can see the data fetching from the grid and assigning into the text boxes but when the function call (imgEdit_click) finished the page does not show the values. Editing functionality can be done in many ways but my scenario is what i explained earlier . I have the checked page there is no Postback action has been called after the method I could not find the solution can anyone help me to figure it out.
Following are my source and code behind codes.
My design Source :
<div class="field">
<asp:TextBox ID="txtareaOfferDesc" runat="server" TextMode="MultiLine" ></asp:TextBox>
</div>
<div class="field">
<asp:TextBox ID="txtTimeStarts" runat="server" CssClass="textfield"></asp:TextBox>
<cc1:CalendarExtender
ID="CalendarExtender2"
runat="server"
TargetControlID="txtTimeStarts"
CssClass="CalendarCSS">
</cc1:CalendarExtender>
<div class="datefld">
<label class="name">Offer end date/time (optional)</label>
<div class="field">
<asp:TextBox ID="txtTimeEnd" runat="server" CssClass="textfield"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender4" runat="server" TargetControlID="txtTimeEnd"
CssClass="CalendarCSS">
</cc1:CalendarExtender> `
<asp:GridView ID="gvShopDeal" runat="server" AutoGenerateColumns="false"
CssClass="tblexistoffer" DataKeyNames="ShopID" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:TemplateField>
<HeaderTemplate >
<asp:CheckBox ID="chkHeader" runat="server" />
<asp:Label ID="lblSelectAll" Text="Select All" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate >
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ShopID" HeaderStyle-Width="10%" HeaderText="Shop ID" />
<asp:BoundField DataField="ShopName" HeaderStyle-Width="40%" HeaderText="Shop Name" />
<asp:BoundField DataField="Street" HeaderStyle-Width="40%" HeaderText="Street" />
<asp:BoundField DataField="City" HeaderText ="City" />
</Columns>
</asp:GridView>
<asp:Button ID="btnCreateDeal" runat="server" Text="Create Offer"
CssClass="grnbtn" OnClientClick="return CheckDealValidation(this)" onclick="btnCreateDeal_Click"></asp:Button>
<asp:Button ID="btnDefCancel" runat="server" Text="Cancel" CssClass="greybtn"></asp:Button>
<asp:UpdatePanel ID="UpdateExistingOffer" runat="server">
<ContentTemplate>
<asp:GridView ID="gvExistingOffers" runat="server" CssClass="tblexistoffer"
AutoGenerateColumns="false" DataKeyNames="OfferID" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:BoundField DataField="OfferID" HeaderText="OfferID" />
<asp:BoundField DataField="Description" HeaderText="OfferName" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:BoundField DataField="OfferType" HeaderText="OfferType" />
<asp:BoundField DataField="StartDate" HeaderText="StartDate">
<ItemStyle CssClass="Hide" />
<HeaderStyle CssClass="Hide" />
</asp:BoundField>
<asp:BoundField DataField="EndDate" HeaderText="EndDate" >
<ItemStyle CssClass="Hide" />
<HeaderStyle CssClass="Hide" />
</asp:BoundField>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" ImageUrl="~/Merchant/images/edit.jpg" runat="server" Width="25" Height="25" onclick="imgbtnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind File :
protected void imgbtnEdit_Click(object sender, ImageClickEventArgs e)
{
ImageButton btndetails = sender as ImageButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
fferIDForShop = Convert.ToInt32(gvExistingOffers.DataKeys[gvrow.RowIndex].Value);
ShopList objShopID = ShopService.GetShopID(OfferIDForShop);
(txtareaOfferDesc.Text) = gvrow.Cells[1].Text.Trim();
txtTimeStarts.Text = gvrow.Cells[4].Text;
txtTimeEnd.Text = gvrow.Cells[5].Text;
}
Thanks
Vijay
Issue is because textboxes are out of Update Panel, So just put everything in update panel it will start functioning or just comment out update panel and then try the same thing.

Confirm delete before deleting dataview's row

I have a GridView which supports deleting. I'd like to add a pop up window with a question like 'Are you sure you want to delete this row?'.
My code:
<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False"
ShowFooter="True" DataKeyNames="ID"
DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
<SelectedRowStyle BackColor="Lime" />
<Columns>
<asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", #"\'"));
}
}
This renders as:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
If I click OK on confirmation window, postback occurs, but nothing happens. If I comment out RowDataBound code, than delete works OK. Code whithout confirmation pop up:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
What am I doing wrong?
I believe this is an example of what you are trying to do. It's cleaner and you don't have to go nutz with the code behind.
In your code you must change ButtonType="Image" to ButtonType="Link" - then onclick="..." will be rendered without javascript:___doPostBack(...) part. And in the GridPaymentMethod_RowDataBound event set something like deleteButton.Text = "<img src=\"path_to_image\" ... />" (use html entities instead of <>).
Or you can use ImageButton with ComamndName="delete" and ConfirmButtonExtender from ASP.NET AjaxToolkit suite.
deleteButton.OnClientClick = string.Format("((!confirm('Are you sure you want to delete payment method {0}?'))?return false);", row.Name.Replace("'", #"\'"));

Resources