LinkButton C# OnClick event not firing within Formview ItemTemplate - c#

I am having an issue with my "save" linkbutton firing and am at a loss. I have included the code for the form and code-behind. I have added some testing to see if the event is firing and it doesn't appear to be so. Any help is appreciated. I am a novice coder so excuse me if there are obvious issues or a better way to proceed. Ultimate goal is to update the entry in the database for the given screen info and then redisplay to updated info.
Again thank you in advance.
UPDATE: I have included the FULL-ish CODE: (removed the sensitive info)
CODEBEHIND:
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class matter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
...
}
protected void fvdoc_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
throw new Exception("Clicked");
}
throw new Exception("i've been Clicked");
}
}
PAGE:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="matter.aspx.cs" Inherits="matter" %>
<!DOCTYPE html>
<html>
<head>
<title>Wasatch Client Matter Index</title>
<link rel="shortcut icon" href="~/favicon.ico" type="image/x-icon" />
<meta name="viewport" charset="utf-8" content="width=device-width, initial-scale=1, user-scalable=no"/>
<!-- Latest compiled and minified CSS -->
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Ubuntu+Condensed' type='text/css' />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<link rel="stylesheet" href="Content/themes/Site.css" />
<!-- Latest compiled JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"/>
</head>
<body>
<div class="navbar">
<div class="row">
<h1 class="col-lg-8 col-lg-offset-2 text-center " style="align-content:center;">Matter Index </h1>
</div>
</div>
<div class="container-fluid">
<form id="form1" runat="server">
<div class="row">
<div class="col-lg-10 col-lg-offset-1 form-group">
<asp:FormView ID="fvdoc" runat="server" DataSourceID="gvdb" OnItemCommand="fvdoc_ItemCommand">
<ItemTemplate>
<h2 class="col-md-12"><asp:Label ID="tbname" runat="server" Text=<%# Bind("docid") %> /> - <asp:Label ID="lbID" runat="server" Text=<%# Bind("sName") %> /></h2>
<div class="left col-md-10">
<legend>Matter Info:</legend>
<div class="form-group"><asp:Label runat="server" Text="Matter" AssociatedControlID="dcname"/>
<asp:TextBox ID="dcname" runat="server" CssClass="form-control" Text=<%# DataBinder.Eval(Container.DataItem,"sDocname") %> Enabled="true"/></div>
</div>
<div class="left col-md-10">
<hr />
<div class="form-group"><asp:Label runat="server" Text="Notes/Comments" AssociatedControlID="dcnotes" />
<asp:TextBox ID="dcnotes" runat="server" Rows="3" TextMode="MultiLine" Text=<%# Bind("sdocdesc") %> Enabled="true"/></div>
</div>
<div class="left col-md-6 col-md-offset-5 txsmall">
<asp:Label runat="server" Text="Filed: " Font-Bold="true" /><asp:Label ID="lblfiledate" runat="server" Text=<%# Bind("dtFiledate") %> CssClass="txsmall" Font-Italic="true" />
<asp:Label runat="server" Text="Modified: " Font-Bold="true" /><asp:Label ID="lblmodify" runat="server" Text=<%# Bind("dtLastModified") + " - " + Bind("susermodified") %> CssClass="txsmall" Font-Italic="true"/>
<asp:Label runat="server" CssClass="txsmall" id="lbltest"/>
</div>
<div class="clear-fix col-md-12">
<div class="form-group">
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" CssClass="clear-fix btn btn-primary" />
<asp:LinkButton runat="server" Text="Move" ID="MoveButton" CssClass="clear-fix btn btn-primary" CausesValidation="False" href="m.aspx" />
<asp:LinkButton runat="server" Text="Home" ID="HomeButton" CssClass="clear-fix btn btn-primary" CausesValidation="False" href="default.aspx"/>
</div>
</div>
</ItemTemplate>
</asp:FormView>
</div>
</div>
<hr class="col-lg-10 col-lg-offset-1" />
</form>
</div>
...
</body>
</html>

Your link button is present inside a formview item template as can be seen below and thus you will not get the individual control event (onclick event of linkbutton). Rather you need to handle the FormView.ItemCommand and do your processing like
<asp:FormView ID="fvdoc" runat="server"
DataSourceID="gvdb" onitemcommand="itemCommandClick">
<ItemTemplate>
.......
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" .........
In code behind handle this like
void itemCommandClick(Object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
LinkButton button = e.CommandSource as LinkButton;
//Do rest of the processing
}
}

Your FormView is missing the EditItemTemplate, like so:
<asp:FormView ID="fvdoc" runat="server" DataSourceID="gvdb" OnItemCommand="fvdoc_ItemCommand">
<ItemTemplate>
<!--... Use readonly controls like Label etc...-->
<asp:LinkButton runat="server" Text="Save" ID="EditButton" CommandName="Edit" CssClass="clear-fix btn btn-primary" />
</ItemTemplate>
<EditItemTemplate>
<!--... Use editable controls like TextBox etc...-->
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" CssClass="clear-fix btn btn-primary" />
</EditItemTemplate>
</asp:FormView>
For the click on the Edit Button, change to Edit mode, then Handle the Save button to save the new values.
See the MSDN docs for more information.

Related

How can I select the record in the grid view and delete or edit this record? In Asp.Net Web Form

How can I select the record in the grid view and delete or edit this record? In Asp.Net Web Form
I want this to be done with the Bootstrap modal
I do this with Entity Framework
I have only been able to code to add
The methods I know for editing and deleting are not suitable for this project and they do not work on Bootstrap Modal
Html Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductControl.aspx.cs" Inherits="AppData.Pages.ProductControl" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="Head" runat="server">
<script src="../Scripts/jquery-3.6.0.slim.min.js"></script>
<script src="../Scripts/Site.js"></script>
</asp:Content>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="container">
<div class="row">
<div class="col-md-12 table-responsive" id="ProductDiv">
<div class="d-flex justify-content-between align-items-center mb-3 mt-3">
<h4>List of Products</h4>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#ModalAdd">
Add Product
</button>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:GridView ID="GridView" runat="server" CssClass="table text-center table-bordered table-hover" HeaderStyle-CssClass="table-dark" AutoGenerateColumns="false" DataKeyNames="Id" OnRowCommand="GridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Font-Size="Small">
<HeaderTemplate>Row</HeaderTemplate>
<ItemTemplate><%# Container.DataItemIndex+1 %></ItemTemplate>
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="Barcode" HeaderText="Barcode" />
<asp:TemplateField HeaderText="Commands" ItemStyle-Font-Size="Small">
<ItemTemplate>
<asp:LinkButton CssClass="btn btn-warning" ID="BtnEdit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton CssClass="btn btn-danger" ID="BtnDelete" runat="server" data-toggle="modal" data-target="#ModalDelete">Delete</asp:LinkButton>
<asp:LinkButton CssClass="btn btn-info" ID="BtnDetail" runat="server">Detail</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="row">
<asp:Label ID="LblNotFound" runat="server" Text="No Product Found" CssClass="col-12 alert alert-danger text-center" Visible="false"></asp:Label>
</div>
</div>
<!-- Modal Add -->
<asp:UpdatePanel ID="UpdatePanelModalAdd" runat="server">
<ContentTemplate>
<div class="modal" id="ModalAdd">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Record</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-6">
<p>Name:</p>
<asp:TextBox ID="Name" placeholder="Name" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-6">
<p>Price:</p>
<asp:TextBox ID="Price" placeholder="Price" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="col-6">
<br />
<p>Type:</p>
<asp:TextBox ID="Type" placeholder="Type" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="col-6">
<br />
<p>Barcode:</p>
<asp:TextBox ID="Barcode" placeholder="Barcode" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="BtnCreate" runat="server" CssClass="btn btn-success" Text="Create" OnClick="BtnCreate_Click" />
<asp:Button ID="BtnCancel" runat="server" CssClass="btn btn-danger" Text="Cancel" data-dismiss="modal" />
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnCreate" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="BtnCancel" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<!-- Modal Detail -->
<asp:UpdatePanel ID="UpdatePanelModalDetail" runat="server">
<ContentTemplate>
<div class="modal" id="ModalDetail">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Detail Record</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-6">
<p>Name:</p>
<asp:Label ID="LblName" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
<div class="col-6">
<p>Price:</p>
<asp:Label ID="LblPrice" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
</div>
<div class="row">
<div class="col-6">
<br />
<p>Type:</p>
<asp:Label ID="LblType" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
<div class="col-6">
<br />
<p>Barcode:</p>
<asp:Label ID="LblBarcode" CssClass="text-secondary" runat="server" Text=""></asp:Label>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-success" Text="Create" OnClick="BtnCreate_Click" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-danger" Text="Cancel" data-dismiss="modal" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<!-- Modal Delete -->
<asp:UpdatePanel ID="UpdatePanelModalDelete" runat="server">
<ContentTemplate>
<div class="modal" id="ModalDelete">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Delete Record</h4>
</div>
<div class="modal-body">
<h6 class="text-center">Are you sure you want to delete this record?</h6>
<br />
<div class="text-center">
<asp:Button ID="Delete" CssClass="btn btn-danger border-2 border-dark" runat="server" Text="Delete" CommandArgument='<%# Eval("Id") %>' CommandName="Delete" />
<button id="Cancel" class="btn btn-light border-2 border-dark" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Delete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
And Backend Code:
using AppData.Models;
using System;
using System.Collections.Generic;
using System.EnterpriseServices;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AppData.Pages
{
public partial class ProductControl : System.Web.UI.Page
{
Models.ProductDbEntities Db = new Models.ProductDbEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (GridView.Rows.Count > 0)
{
LblNotFound.Visible = false;
}
else
{
GridView.DataSource = Db.TblProducts.ToList();
GridView.DataBind();
}
}
protected void BtnCreate_Click(object sender, EventArgs e)
{
TblProduct Row = new TblProduct();
Row.Name = Name.Text;
Row.Price = Price.Text;
Row.Type = Type.Text;
Row.Barcode = Convert.ToInt64(Barcode.Text);
Db.TblProducts.Add(Row);
Db.SaveChanges();
Response.Redirect("ProductControl.aspx");
}
protected void BtnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("Pages/ProductControl.aspx");
}
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id = e.CommandArgument;
if (e.CommandName == "Delete")
{
Int64 Id = Convert.ToInt64(id);
var Row = Db.TblProducts.FirstOrDefault(n => n.Id == Id);
Db.TblProducts.Remove(Row);
Db.SaveChanges();
Response.Redirect("DataControl.aspx");
GridView.DataSource = Db.TblProducts.ToList();
GridView.DataBind();
}
}
}
}
I understand your approach, but if you are using bootstrap modals you need to write a little bit more code.
One way to achieve this is by following the next steps:
In the Delete modal add a hidden field to hold the selected productId and an event handler for the delete button:
<div class="modal-body">
<h6 class="text-center">Are you sure you want to delete this record?</h6>
<br />
<!--add this inside delete modal -->
<input type="hidden" id="productIdToDelete" runat="server" />
<div class="text-center">
<!-- remove CommandArgument and CommandName from the Delete button. They are useless in the popup. -->
<!-- add an event handler to OnClick-->
<asp:Button ID="Delete" CssClass="btn btn-danger border-2 border-dark" runat="server" Text="Delete" OnClick="BtnDelete_Click" />
...
Create event handlers for when the modal is opened in order to propagate the productId from the current row in the grid to the modal:
<script src="../Scripts/Site.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
//use a jquery selector to assign an event handler to all Delete Buttons found on the page (nottice they all start with the same prexif)
$("[id*=MainContent_GridView_BtnDelete]").click(function () {
//get the id of the product from the selected row first cell and assign it to the hidden field in the modal
$("#MainContent_productIdToDelete").val($(this).closest('tr').find('td').eq(0).html());
});
});
</script>
Finally, handle the delete event in the code behind:
protected void BtnDelete_Click(object sender, EventArgs e)
{
string idVal = Request.Form[productIdToDelete.UniqueID];
var id = Convert.ToInt64(idVal);
// implement delete logic ...
}
Use the same approach for Edit. (Look at this example.)

ASP.NET dropdownlist selectedIndexChanged not getting triggered

I am trying to create a form as part of a website. In the form the user is shown a dropdownlist with serveral options. If the user chooses the "Other" option, then they should be presented with a text box to fill the description of the "other" choice.
My idea was to hide the div that contains the text box and enable it when the user changes the dropdown list choice to "other".
I am having an issue where in asp.net the dropdownlist "selectedindexchanged" event is not being triggered. Below is the HTML code and the cs code.
<%# Page Title="" Language="C#" MasterPageFile="~/master/Site1.Master" AutoEventWireup="true" CodeBehind="form.aspx.cs" Inherits="Project.forms.form" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="menu" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Banner" runat="server">
<img src="../../image.jpg" class="img-responsive" alt="Responsive image" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<h2 class="branding_orange">Form</h2>
<div class="alert alert-danger" name="warningDiv" style="margin-top:10px" id="warningDiv" role="alert" runat="server">
<p name="warningMsg" id="warningMsg" runat="server"></p>
</div>
<form id="compliantForm" role="form" class="form" runat="server" data-toggle="validator" onsubmit="return validation();">
<div class="row">
.
.
.
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="form-group">
<label for="person-submitting-select">Is the person submitting this complaint an: <b style="color:red">*</b></label>
<asp:DropDownList ID="cboPersonSubmitting" runat="server" AutoPostBack = "True" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<asp:ListItem Text="select" Value="0" />
<asp:ListItem Text="Employee" Value="1" />
<asp:ListItem Text="Customer" Value="2" />
<asp:ListItem Text="Other" Value="3" />
</asp:DropDownList>
</div>
</div>
.
.
.
.
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project.forms
{
public partial class form : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cboPersonSubmitting.AutoPostBack = true;
warningDiv.Visible = false;
warningMsg.InnerHtml = "";
}
.
.
.
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
if (cboPersonSubmitting.SelectedIndex == 3)
{
whoSubmittingDiv.Visible = true;
}
else
{
whoSubmittingDiv.Visible = false;
}
}
}
}
Based on my test, you can try the following code to show textbox when you choose Other in the dropdownlist.
Html:
<form id="form1" runat="server">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="form-group">
<label for="person-submitting-select">Is the person submitting this complaint an: <b style="color:red">*</b></label>
<asp:DropDownList ID="cboPersonSubmitting" runat="server" AutoPostBack = "True" OnSelectedIndexChanged="cboPersonSubmitting_SelectedIndexChanged">
<asp:ListItem Text="select" Value="0" />
<asp:ListItem Text="Employee" Value="1" />
<asp:ListItem Text="Customer" Value="2" />
<asp:ListItem Text="Other" Value="3" />
</asp:DropDownList>
<div class="Submitdiv" id="thediv" runat="server" visible="false">
<asp:TextBox ID="txtInput" runat="server" ></asp:TextBox>
</div>
</div>
</div>
</form>
C# code:
protected void cboPersonSubmitting_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboPersonSubmitting.SelectedIndex == 3)
{
thediv.Visible = true;
}
else
{
thediv.Visible = false;
}
}
Result:

Cant get ListView to refresh on postback

I have a very simple asp.net webform page with a listview, I can not make the listView refresh on postback, only if I make a new request. I guess the listView gets its content from the viewstate or something. I databind in the Page_Load event, and i have also tried the Page_Init event. No difference.
I have probably been through the first 50 Google search results, and nothing seems to work.
How do i force the listview to refresh on postback?
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RSS_Reader.Default" %>
<%# Import namespace="RSS_Reader.Extensions" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>RSS Reader</title>
<link rel="shortcut icon" href="favicon.ico" />
<link href="css/main.css" rel="stylesheet" />
<script src="js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="js/App.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="horizontal-menu">
<ul id="horizontal-menu-list">
<li id="add-feed">Add Feed
<ul>
<li>
<input type="text" placeholder="Feed URL" /><button class="button green">Add</button>
</li>
</ul>
</li>
<li>Add Group</li>
<li>Settings</li>
</ul>
<div id="global-search">
<input type="text" id="search" placeholder="Search" />
</div>
<div style="clear: both"></div>
</div>
<div id="feeds">
<div id="feed-filter">
<asp:TextBox ID="feedUrl" runat="server" placeholder="Feed URL"></asp:TextBox>
<asp:Button ID="ThisIsAUniqueNameForAButton" runat="server" CssClass="button green" Text="Subscribe" OnClick="subscribeToFeed" />
</div>
<div id="feed-wrapper">
<asp:ListView ID="FeedCollection" runat="server">
<ItemTemplate>
<div><div class="feed-collection-icon"></div><asp:Label runat="server" ID="listFeedTitle" Text='<%# Bind("Title") %>'></asp:Label></div>
</ItemTemplate>
</asp:ListView>
</div>
</div>
<div id="content">
<div id="feed-title">Version2 - IT For Professionelle</div>
<div id="nodes">
<asp:GridView ID="nodesGridview" OnSorting="nodesGridview_Sorting" runat="server" OnSortCommand="SortGrid" AllowSorting="True" AutoGenerateColumns="false">
<EmptyDataTemplate>
No feed.
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<ItemTemplate>
<div class="node-icon"></div> <%# XPath("title") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="description">
<ItemTemplate>
<%# XPath("description").ToString().Truncate(50) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date" SortExpression="pubDate">
<ItemTemplate>
<%# XPath("pubDate").ToString().toDate() %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="reading-pane">
<asp:Label ID="readingPaneTitle" runat="server" Text="Label"></asp:Label>
</div>
</div>
<div id="footer">
Copyright © 2014 - Mads O. Nielsen
</div>
</div>
</form>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Diagnostics;
using System.Data.Entity;
using System.Data;
using System.IO;
using RSS_Reader.FeedCollection;
using RSS_Reader.FeedItem;
namespace RSS_Reader
{
public partial class Default : System.Web.UI.Page
{
private XmlDataSource feedItems;
private FeedReader feedReader;
protected void Page_Init(object sender, EventArgs e)
{
Debug.WriteLine("Page_Init");
if (!IsPostBack)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
RSS_Reader.Model db = new RSS_Reader.Model();
//var feedQuery = from emp in db.Feeds select emp;
//List<Feeds> empList = feedQuery.ToList();
FeedCollection.DataSource = db.Feeds.ToList();
feedReader = new FeedReader();
feedReader.load("http://www.version2.dk/it-nyheder/rss");
feedItems = new XmlDataSource();
feedItems.EnableCaching = false;
feedItems.ID = "feedItems";
feedItems.Data = feedReader.feed.OuterXml;
feedItems.XPath = "rss/channel/item";
nodesGridview.Width = new Unit(100.00, UnitType.Percentage);
nodesGridview.DataSource = feedItems;
FeedCollection.DataBind();
nodesGridview.DataBind();
}
protected void subscribeToFeed(object sender, EventArgs e)
{
FeedManager feedManager = new FeedManager();
feedManager.subscribe(feedUrl.Text);
}
protected void nodesGridview_Sorting(object sender, GridViewSortEventArgs e)
{
Debug.WriteLine("Sorting");
}
}
}
if it cant refresh the ListView because of save it into ViewState you can set EnableViewState property to False then server refresh it in all postback

Access TextBox in DataList by ID from Button-Click handler in codebehind

I have a textbox which is kept inside Datalist. I need to find it via ID, so that i can insert text written to that textbox to the database.Here is my aspx page containing textbox.
<asp:Content ID="Content1" ContentPlaceHolderID="ccont" Runat="Server">
<div id="ccont">
<asp:DataList ID="mydatalist" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div id="wholeC">
<div id="ctop">
<div id="lft_l">
<div id="lft_c_top">
<asp:Image runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="250px" Width="300px" />
<br/>
</div>
<div id="lft_c_down">
<b>Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"products") %>' runat="server" />
<br/>
<b>brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
<b>Price:</b>
<asp:Label ID="Label1" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
</div>
</div>
<div id="lft_r">
<b>Details:</b>
<asp:Label ID="Label2" Text='<%#DataBinder.Eval(Container.DataItem,"description") %>' runat="server" />
</div>
</div>
<div id="cmt">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="620" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
The Textbox with ID="tb_cmt" is the text box i want to access in my code behind as:
protected void cmt_Click(object sender, EventArgs e)
{
// how to get the TextBox?
sq.connection();
SqlCommand cmd = new SqlCommand("insert into comment(ecomment,sid) values(#myecomment,#mysid)", sq.con);
cmd.Parameters.AddWithValue("#myecomment",tb_cmt.text)//but here tb_cmt is not recognized.
}
You can use the NamingContainer property of the button that was clicked to get the DataListItem. Then you just have to use FindControl to get the reference to your TextBox:
protected void cmt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
DataListItem item = (DataListItem) btn.NamingContainer;
TextBox txt = (TextBox) item.FindControl("tb_cmt");
//... save
}

refreshing entire page from within an updatepanel

Here's my situation. I have a web forms page, and it's getting annoying when the entire page scrolls to the top every time you click a control, so I'm trying to apply update panels to my page.
The submit button may or may not be click-able depending on whether or not the contents of individual update panels are in a proper state.
When the submit button is clicked, It can potentially affect any of the controls on the page.
I understand that I can do some of this with the <triggers> tag element of the update panel, but I don't want to have to put everything on the page into an update panel with it's own trigger, I'd rather that the submit button just reload the entire page.
For the sake of simplicity I've put together a sample project to represent my page. It has a "reset" button, to represent the "submit" button.
The Master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true" />
<div class="page">
<div class="header">
<div class="title">
<h1>
My ASP.NET Application
</h1>
</div>
<div class="loginDisplay">
<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
<AnonymousTemplate>
[ Log In ]
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
[ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
</LoggedInTemplate>
</asp:LoginView>
</div>
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
<asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
</Items>
</asp:Menu>
</div>
</div>
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
<div class="clear">
</div>
</div>
<div class="footer">
</div>
</form>
</body>
</html>
The default page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Label runat=server Text="This lable represents things not in update panels" ID="label1"></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat=server>
<ContentTemplate>
<table>
<tr>
<td><asp:Button ID="button1" runat="server" OnClick="Button1_click" Text="Button 1" /></td>
<td><asp:TextBox ID="textBox1" runat="server" Text="StartText" Enabled="false" /></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat=server>
<ContentTemplate>
<table>
<tr>
<td><asp:Button ID="button2" runat="server" OnClick="Button2_click" Text="Button 2" /></td>
<td><asp:TextBox ID="textBox2" runat="server" Text="StartText" Enabled="false" /></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanelReset" runat=server>
<ContentTemplate>
<asp:Button ID="reset" runat="server" OnClick="Reset_click" Text="reset" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="button1" EventName="click" />
<asp:AsyncPostBackTrigger ControlID="button2" EventName="click" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
The code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_click(object sender, EventArgs e)
{
textBox1.Enabled = !textBox1.Enabled;
reset.Enabled = !textBox1.Enabled && !textBox2.Enabled;
}
protected void Button2_click(object sender, EventArgs e)
{
textBox2.Enabled = !textBox2.Enabled;
reset.Enabled = !textBox1.Enabled && !textBox2.Enabled;
}
protected void Reset_click(object sender, EventArgs e)
{
textBox1.Text = "StartText";
textBox2.Text = "StartText";
label1.Text = "reset button clicked";
}
}
}
Just add a PostBackTrigger to the last UpdatePanel.
<asp:PostBackTrigger ControlID="reset" />

Categories

Resources