I have a GridView with a sql Source, which is bound to a searchbox. The problem is that on Postback the GridView disappears. I have tried to DataBind the GridView in the PageLoad event but the problem is that the Data is coming from the searchbox so On Postback it takes out the value of the Searchbox and searches for it.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Archiv.aspx.cs" Inherits="AutoVerwaltungASP.Archiv" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox id="searchbox" Value="Search..." runat="server" ForeColor="Gray" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" />
<asp:Button Text="Suchen" runat="server" ID="btnSearch" OnClick="btnSearch_Click" Height="34px" Width="90px" Font-Size="Small"/>
<asp:Button Text="Reset" runat="server" ID="btnClear" OnClick="btnClear_Click" Height="34px" Width="90px" Font-Size="Small"/>
<cc1:AutoCompleteExtender ServiceMethod="markensuchen"
MinimumPrefixLength="2"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="searchbox"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSourceAutos" ForeColor="Black" GridLines="Vertical" DataKeyNames="m_id" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="m_id" HeaderText="m_id" SortExpression="m_id" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="m_name" HeaderText="m_name" SortExpression="m_name" />
<asp:BoundField DataField="m_h_id" HeaderText="m_h_id" SortExpression="m_h_id" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceAutos" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [m_id], [m_name], [m_h_id] FROM [marke]" FilterExpression="m_name LIKE '%{0}%'" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [marke] WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" InsertCommand="INSERT INTO [marke] ([m_name], [m_h_id]) VALUES (#m_name, #m_h_id)" OldValuesParameterFormatString="original_{0}" UpdateCommand="UPDATE [marke] SET [m_name] = #m_name, [m_h_id] = #m_h_id WHERE [m_id] = #original_m_id AND [m_name] = #original_m_name AND [m_h_id] = #original_m_h_id" >
<DeleteParameters>
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</DeleteParameters>
<FilterParameters>
<asp:ControlParameter Name="m_name" ControlID="searchbox" PropertyName="Text" />
</FilterParameters>
<InsertParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="m_name" Type="String" />
<asp:Parameter Name="m_h_id" Type="Int32" />
<asp:Parameter Name="original_m_id" Type="Int32" />
<asp:Parameter Name="original_m_name" Type="String" />
<asp:Parameter Name="original_m_h_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
public partial class Archiv : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
GridView1.DataBind();
}
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> markensuchen(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select m_name from marke where " +
"m_name like #searchbox + '%'";
cmd.Parameters.AddWithValue("#searchbox", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> marken = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
marken.Add(sdr["m_name"].ToString());
}
}
conn.Close();
return marken;
}
}
}
private string SearchString = "";
public string HighlightText(string InputTxt)
{
string Search_Str = searchbox.Text;
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
}
public string ReplaceKeyWords(Match m)
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SearchString = searchbox.Text;
}
protected void btnClear_Click(object sender, EventArgs e)
{
searchbox.Text = "";
SearchString = "";
GridView1.DataBind();
}
}
}
Related
I have 2 JQGrids on my ASPX page. When an Invoice is selected on the top grid, it loads the corresponding data on the second.
My issue is with exporting. When I export the page using SelectPDF, the 2nd Grid View is always empty.
Here is what it looks like on the page:
...and this is what the exported PDF looks like, there is no data in the second grid.
Here is the ASPX code:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="Invoicing" Codebehind="Invoicing.aspx.cs" EnableEventValidation="false" %>
<%# Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="themes/CustomStyles.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/jquery-ui.css" />
<link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Indigo2.Properties.Settings.Constr %>"
SelectCommand="SELECT [invoice_number],[invoice_date],[custid],[inv_splitter] FROM [Indigo].[dbo].[invoices]" CancelSelectOnNullParameter="false"
UpdateCommand=""
DeleteCommand="">
<UpdateParameters>
<asp:Parameter Name="invoice_number" Type="Int32" />
<asp:Parameter Name="invoice_date" Type="DateTime" />
<asp:Parameter Name="custid" Type="String" />
<asp:Parameter Name="inv_splitter" Type="String" />
</UpdateParameters>
<DeleteParameters>
</DeleteParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:Indigo2.Properties.Settings.Constr %>"
SelectCommand="SELECT [inv_item_id],[description],[unit_sell],[qty],[inv_section],[inv_orderby],[inv_splitter],[ref_date_start],[ref_date_end],[custid],[cust_po],[invoice_number], unit_sell * qty as Price FROM [Indigo].[dbo].[invoice_items] WHERE (invoice_number = #invoice_number) " CancelSelectOnNullParameter="false"
UpdateCommand="UPDATE Invoice_items SET cust_po=#cust_po, description=#description, ref_date_start=CONVERT(datetime, #ref_date_start, 105), ref_date_end=CONVERT(datetime, #ref_date_end, 105), unit_sell=#unit_sell, qty=#qty WHERE inv_item_id=#inv_item_id"
DeleteCommand="DELETE FROM Invoice_items WHERE inv_item_id=#inv_item_id">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="invoice_number" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="inv_item_id" Type="Int32" />
<asp:Parameter Name="cust_po" Type="String" />
<asp:Parameter Name="description" Type="String" />
<asp:Parameter Name="ref_date_start" Type="DateTime" />
<asp:Parameter Name="ref_date_end" Type="DateTime" />
<asp:Parameter Name="unit_sell" Type="Decimal" />
<asp:Parameter Name="qty" Type="Int32" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="inv_item_id" Type="Int32" />
<asp:Parameter Name="cust_po" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<br />
<trirand:JQGrid runat="server" ID="JQGrid1" DataSourceID="SqlDataSource1" Width="1200"
OnRowSelecting="JQGrid1_RowSelecting">
<Columns>
<trirand:JQGridColumn DataField="invoice_number" HeaderText="ID" PrimaryKey="True" Width="100" />
<trirand:JQGridColumn DataField="invoice_date" Editable="true" DataFormatString="{0:d}" Width="100"/>
<trirand:JQGridColumn DataField="custid" Editable="true" Width="100"/>
</Columns>
<ToolBarSettings ShowEditButton="true" ShowRefreshButton="True" ShowAddButton="true" ShowDeleteButton="true" ShowSearchButton="True" />
</trirand:JQGrid>
<br />
<trirand:JQGrid runat="server" ID="JQGrid2" DataSourceID="SqlDataSource2" Width="1200" Height="100%" maxHeight="300" hidegrid="true" ondatarequested="JQGrid2_DataRequested">
<Columns>
<trirand:JQGridColumn CSSClass="indent" DataField="description" Editable="true" Width="800"/>
<trirand:JQGridColumn DataField="inv_section" Editable="true" />
<trirand:JQGridColumn DataField="ref_date_start" Editable="true" DataFormatString="{0:d}" Width="200"/>
<trirand:JQGridColumn DataField="ref_date_end" Editable="true" DataFormatString="{0:d}" Width="200"/>
<trirand:JQGridColumn DataField="cust_po" Editable="true" />
<trirand:JQGridColumn DataField="unit_sell" Editable="true" DataFormatString="{0:c}" Width="200"/>
<trirand:JQGridColumn DataField="qty" Editable="true" Width="200"/>
<trirand:JQGridColumn DataField="price" Editable="false" DataFormatString="{0:c}" Width="200" >
</trirand:JQGridColumn>
</Columns>
<PagerSettings PageSize="12" />
<GroupSettings CollapseGroups="false">
<GroupFields>
<trirand:GroupField
DataField="inv_section"
HeaderText="<b>{0}</b>"
GroupSortDirection="Asc"
ShowGroupColumn="false"
ShowGroupSummary="true"/>
<trirand:GroupField
DataField="cust_po"
HeaderText="PO Reference: <b>{0}</b>"
GroupSortDirection="Asc"
ShowGroupColumn="false"
ShowGroupSummary="false"/>
</GroupFields>
</GroupSettings>
<AppearanceSettings ShowFooter="true" />
<ToolBarSettings ShowEditButton="true" ShowRefreshButton="True" ShowAddButton="true" ShowDeleteButton="true" ShowSearchButton="True" />
</trirand:JQGrid>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="ExportToPDFButton" Text="Export to PDF" OnClick="BtnCreatePdf_Click" />
...and here is the underlying code
using System;
using System.Web.UI;
using Trirand.Web.UI.WebControls;
using System.IO;
using System.Data;
using SelectPdf;
using System.Web;
public partial class Invoicing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JQGrid2.Visible = true; //was false!!!!!!!!!!!!!!
if (Session["invoice_number"] != null)
{
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
}
}
protected void JQGrid2_DataRequested(object sender, Trirand.Web.UI.WebControls.JQGridDataRequestedEventArgs e)
{
DataTable dt = e.DataTable; // get only the current page data
double poTotal = 0;
foreach (DataRow row in dt.Rows)
{
double poValue = (double)row["price"];
poTotal += poValue;
}
string formattedMoneyValue = String.Format("{0:C}", poTotal);
JQGrid2.Columns.FromDataField("price").FooterValue = formattedMoneyValue.ToString();
JQGrid2.Columns.FromDataField("qty").FooterValue = "Total:";
}
protected void JQGrid1_RowSelecting(object sender, Trirand.Web.UI.WebControls.JQGridRowSelectEventArgs e)
{
Session["invoice_number"] = JQGrid1.SelectedRow;
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
}
//Start of Select PDF Code//
private bool startConversion = false;
protected void BtnCreatePdf_Click(object sender, EventArgs e)
{
startConversion = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (startConversion)
{
Session["invoice_number"] = JQGrid1.SelectedRow;
JQGrid2.Visible = true;
SqlDataSource2.SelectParameters["invoice_number"].DefaultValue = Session["invoice_number"] as string;
// get html of the page
TextWriter myWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(myWriter);
base.Render(htmlWriter);
// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();
// create a new pdf document converting the html string of the page
PdfDocument doc = converter.ConvertHtmlString(
myWriter.ToString(), Request.Url.AbsoluteUri);
// save pdf document
doc.Save(Response, false, "Sample.pdf");
// close pdf document
doc.Close();
}
else
{
// render web page in browser
base.Render(writer);
}
}
}
Please can someone help me, with what I need to do so that the data from the second grid is passed to the PDF when exported.
UPDATE:
If I hardcode the default value for the datasource on the second grid it exports the correct info.
<SelectParameters>
<asp:Parameter DefaultValue="1000" Name="invoice_number" Type="Int32" />
</SelectParameters>
For some reason when I export, it seems to be clearing this parameter value, if I set it dynamically.
The SelectPdf convert loads your web page using a new Session, so it does not know your dynamically set parameters. You need to send them in the url, if possible.
I want to modify items in gridview by update command but in same page i have also a textbox with required validation.
i'm unable to update in gridview when require validation occur in textbox Control
And Source Code here...
<div class="row">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="Button1_Click"
ValidationGroup="btn" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Text="Reset" OnClick="Button2_Click"
CausesValidation="False" />
<asp:Button ID="Button3" runat="server" CssClass="btn btn-primary" Text="Show" CausesValidation="False"
OnClick="Button3_Click" />
</div>
</form> </div> </div>
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover table-responsive table-condensed table-bordered"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SqlDataSource1" Visible="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="Loc" HeaderText="Location" SortExpression="Loc" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mycon %>"
SelectCommand="SELECT * FROM [location]" DeleteCommand="Delete From Location Where Id=#id"
UpdateCommand="update location set loc=#loc where id=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="TextBox1" Name="id" PropertyName="Text" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="loc" />
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>
and cs code here
protected void Button1_Click(object sender, EventArgs e)
{
string qry = "insert into location (loc)values(#loc) ";
SqlConnection con = Connection.Getconnection();
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#loc", TextBox1.Text);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Successfully Add')</script>");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Error')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
}
Please try to add try catch for button1_click to catch Exceptions.
Validation group has an effect only when the value of the CausesValidation property is set to true.and validation group need to specify a value
Please Refer this Link
The Title sounds wierd but thats what is actually happening.
I found people with similar problems but there was no answer on these pages.
I have a DetailsView Control which is bound to a ObjectDataSource
Code:
<asp:DetailsView ID="DetailsView1" runat="server" BackColor="#7B7C95" BorderColor="White" BorderWidth="1px" CellPadding="2" ForeColor="White" GridLines="None" Style="height: 80%; width: 80%" AutoGenerateRows="False" DataSourceID="UserTableObjectDataSource" Font-Bold="True" Font-Names="Tahoma" AutoGenerateEditButton="True" OnItemUpdating="DetailsView1_ItemUpdating">
<AlternatingRowStyle BackColor="#393847" />
<FieldHeaderStyle VerticalAlign="Middle" />
<Fields>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<div style="width: 50%; height: auto; overflow: auto;">
<asp:Image ID="Image1" runat="server" AlternateText="No Image Added" ImageUrl='<%# Eval("ImageUrl") %>' />
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" ReadOnly="True" />
<asp:BoundField DataField="PackagesBooked" HeaderText="Packages Booked" SortExpression="PackagesBooked" ReadOnly="True">
<ItemStyle Font-Underline="True" />
</asp:BoundField>
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
</Fields>
<FooterStyle BackColor="Tan" VerticalAlign="Middle" />
<HeaderStyle BackColor="Tan" Font-Bold="True" VerticalAlign="Middle" />
<PagerStyle BackColor="Silver" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
</asp:DetailsView>
<asp:ObjectDataSource ID="UserTableObjectDataSource" runat="server" SelectMethod="getUser" TypeName="HolidaysForYou.DAL.DbHandler" UpdateMethod="updateUser" ValidateRequestMode="Enabled">
<SelectParameters>
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="PhoneNumber" Type="String" />
<asp:SessionParameter Name="username" SessionField="Username" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
the update method looks like this
public static void updateUser(string Email, string PhoneNumber, string username)
{
string usernameLower = username.ToLower();
string queryString = "Update [UserTable] SET Email='" + Email + "',PhoneNumber='" + PhoneNumber + "' WHERE ([Name] = '" + usernameLower + "')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.BeginExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
}
When i run the program in debug mode and go slowly step by step, the program works perfectly if i just run it there is no change in the Db.
i also tried calling the updateUser function from the DetailsView1_ItemUpdating function like :
protected void DetailsView1_ItemUpdating(object sender, System.Web.UI.WebControls.DetailsViewUpdateEventArgs e)
{
try
{
string newEmail = (string)e.NewValues["Email"];
string newPhoneNumber = (string)e.NewValues["PhoneNumber"];
if (!UserHomeValidate.userUpdateValidate(newEmail, newPhoneNumber))
{
e.Cancel = true;
Error.Visible = true;
}
else
UserHomeValidate._updateUser(newEmail, newPhoneNumber, Session["Username"].ToString().ToUpper());
}
catch (Exception exception)
{
Utility.LogFile.CreateLogFile(exception);
}
}
where _updateUser is exactly the same as updateUser and still the dataBase is not changed.... this might have something to do with postback but i dont know how that works..
This is getting frustrating a lil help would be appreciated..
Solved the issue...
just had to add
if (!Page.IsPostBack)
DetailsView1.DataBind();
to the page_Load to avoid binding at the postback as then the old values will be passed...
The user comes to this page to edit/update details for particular Employee. The employee details are shown in a DetailsView, which is bound to Northwind database. The problem is when I click Edit and change some data and then click Update - the fields returns to the initial state as if nothing has changed.
Webform code:
<form id="form1" runat="server">
<asp:DetailsView ID="DetailsViewEditEmployee"
runat="server"
AutoGenerateRows="False"
Height="50px"
Width="314px"
OnItemCommand="DetailsViewEditEmployee_ItemCommand"
OnModeChanging="DetailsViewEditEmployee_ModeChanging"
OnItemUpdating="DetailsViewEditEmployee_ItemUpdating"
OnItemUpdated="DetailsViewEditEmployee_ItemUpdated" >
<Fields>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="False" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:CommandField ButtonType="Button" CausesValidation="False" ShowEditButton="True" />
</Fields>
</asp:DetailsView>
CustomerID:
<asp:Literal Text="text" runat="server" id="LiteralCustomerId" Mode="Encode" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = #EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [FirstName], [Title], [Address], [City]) VALUES (#LastName, #FirstName, #Title, #Address, #City)" SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title], [Address], [City] FROM [Employees]" UpdateCommand="UPDATE [Employees] SET [LastName] = #LastName, [FirstName] = #FirstName, [Title] = #Title, [Address] = #Address, [City] = #City WHERE [EmployeeID] = #EmployeeID">
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Address" Type="String" />
<asp:Parameter Name="City" Type="String" />
<asp:Parameter Name="EmployeeID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</form>
Code behind:
public partial class EmployeesEdit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["Id"] == null)
{
Response.Redirect("EmployeesRepeater.aspx");
}
this.LiteralCustomerId.Text = Request.Params["id"];
var id = int.Parse(Request.Params["id"]);
using (var context = new NorthwindEntities())
{
var employees = context.Employees;
var empToList = employees.ToList();
var current =
from emp in empToList
where emp.EmployeeID == id
select emp;
this.DetailsViewEditEmployee.DataSource = current;
this.DetailsViewEditEmployee.DataBind();
}
}
protected void DetailsViewEditEmployee_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
if (e.NewMode == DetailsViewMode.Edit)
{
this.DetailsViewEditEmployee.ChangeMode(e.NewMode);
this.DetailsViewEditEmployee.DataBind(); // add this and check
}
if (e.CancelingEdit)
{
this.DetailsViewEditEmployee.ChangeMode(DetailsViewMode.ReadOnly);
this.DetailsViewEditEmployee.DataBind(); // add this and check
}
}
protected void DetailsViewEditEmployee_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
for (int i = 0; i < e.NewValues.Count; i++)
{
if (e.NewValues[i] != null)
{
e.NewValues[i] = Server.HtmlEncode(e.NewValues[i].ToString());
}
}
}
protected void DetailsViewEditEmployee_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
this.DetailsViewEditEmployee.DataBind();
}
protected void DetailsViewEditEmployee_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("New"))
{
this.DetailsViewEditEmployee.ChangeMode(DetailsViewMode.Insert);
this.DetailsViewEditEmployee.DataBind();
}
else if (e.CommandName.Equals("Edit"))
{
this.DetailsViewEditEmployee.ChangeMode(DetailsViewMode.Edit);
this.DetailsViewEditEmployee.DataBind();
}
}
}
You should databid the DetailsView only on the initial load, not on every postback:
if(!IsPostBack)
{
using (var context = new NorthwindEntities())
{
var employees = context.Employees;
var empToList = employees.ToList();
var current =
from emp in empToList
where emp.EmployeeID == id
select emp;
this.DetailsViewEditEmployee.DataSource = current;
this.DetailsViewEditEmployee.DataBind();
}
}
Page_Load is triggered before events, by databinding it again you prevent events from being fired.
I have been coding a gridview into my website for a day or so now but simply cannot get it to work, fixing one problem just creates more issues.
When selecting edit on a particular record, the gridview goes into the edit item template as it should, but once I have changed the records I want to change, I click update, and then once the gridview returns to item template, all fields on the record are empty?
Here is the GridView code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="PlantID"
DataSourceID="SqlDataSource1" AllowSorting="True" CellPadding="4"
ForeColor="#333333" GridLines="None" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
<asp:CommandField ButtonType="Button" ShowCancelButton="true" />
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
<asp:BoundField DataField="PlantID" HeaderText="PlantID" InsertVisible="False"
ReadOnly="True" SortExpression="PlantID" />
<asp:TemplateField HeaderText="Latin Name">
<ItemTemplate>
<%# Eval("LatinName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtLatinName" Text='<%# Eval("LatinName") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Popular Name">
<ItemTemplate>
<%# Eval("PopularName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPopularName" Text='<%# Eval("PopularName")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Season">
<ItemTemplate>
<%# Eval("Season") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSeason" Text='<%# Eval("Season") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Aftercare">
<ItemTemplate>
<%# Eval("Aftercare") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtAftercare" Text='<%# Eval("Aftercare") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Categories">
<ItemTemplate>
<%# Eval("Categories") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtCategories" Text='<%# Eval("Categories") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%# Eval("Description") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtDescription" Text='<%# Eval("Description") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Uses">
<ItemTemplate>
<%# Eval("Uses") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtUses" Text='<%# Eval("Uses") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FoliageColour">
<ItemTemplate>
<%# Eval("FoliageColour") %>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox runat="server" ID="txtFoliageColour" Text='<%# Eval("FoliageColour") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Flower Colour">
<ItemTemplate>
<%# Eval("FlowerColour") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtFlowerColour" Text='<%# Eval("FlowerColour") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FloweringPeriod">
<ItemTemplate>
<%# Eval("FloweringPeriod") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtFloweringPeriod" Text='<%# Eval("FloweringPeriod") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Height">
<ItemTemplate>
<%# Eval("Height") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtHeight" Text='<%# Eval("Height") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Spread">
<ItemTemplate>
<%# Eval("Spread") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSpread" Text='<%# Eval("Spread") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Instructions">
<ItemTemplate>
<%# Eval("Instructions") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtInstructions" Text='<%# Eval("Instructions") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<%# Eval("Price") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPrice" Text='<%# Eval("Price") %>' />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM [Plants]"
DeleteCommand="DELETE FROM [Plants] WHERE [PlantID] = ?"
InsertCommand="INSERT INTO [Plants] ([PlantID], [LatinName], [PopularName], [Season], [Aftercare], [Categories], [Description], [Uses], [FoliageColour], [FlowerColour], [FloweringPeriod], [Height], [Spread], [Instructions], [Price]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
UpdateCommand="UPDATE [Plants] SET [LatinName] = ?, [PopularName] = ?, [Season] = ?, [Aftercare] = ?, [Categories] = ?, [Description] = ?, [Uses] = ?, [FoliageColour] = ?, [FlowerColour] = ?, [FloweringPeriod] = ?, [Height] = ?, [Spread] = ?, [Instructions] = ?, [Price] = ? WHERE [PlantID] = ?">
<DeleteParameters>
<asp:Parameter Name="PlantID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="PlantID" Type="Int32" />
<asp:Parameter Name="LatinName" Type="String" />
<asp:Parameter Name="PopularName" Type="String" />
<asp:Parameter Name="Season" Type="String" />
<asp:Parameter Name="Aftercare" Type="String" />
<asp:Parameter Name="Categories" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="Uses" Type="String" />
<asp:Parameter Name="FoliageColour" Type="String" />
<asp:Parameter Name="FlowerColour" Type="String" />
<asp:Parameter Name="FloweringPeriod" Type="String" />
<asp:Parameter Name="Height" Type="String" />
<asp:Parameter Name="Spread" Type="String" />
<asp:Parameter Name="Instructions" Type="String" />
<asp:Parameter Name="Price" Type="Decimal" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="LatinName" Type="String" />
<asp:Parameter Name="PopularName" Type="String" />
<asp:Parameter Name="Season" Type="String" />
<asp:Parameter Name="Aftercare" Type="String" />
<asp:Parameter Name="Categories" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="Uses" Type="String" />
<asp:Parameter Name="FoliageColour" Type="String" />
<asp:Parameter Name="FlowerColour" Type="String" />
<asp:Parameter Name="FloweringPeriod" Type="String" />
<asp:Parameter Name="Height" Type="String" />
<asp:Parameter Name="Spread" Type="String" />
<asp:Parameter Name="Instructions" Type="String" />
<asp:Parameter Name="Price" Type="Decimal" />
<asp:Parameter Name="PlantID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
Here is the code behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
public partial class Staff : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDataPlant();
}
}
private void BindDataPlant()
{
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("~/App_Data/LincolnGardenCentre.accdb;"));
try
{
Conn.Open();
if (Conn.State.ToString() == "Open")
Page.Title = "Connection Successful";
else
Page.Title = "Connection Unsuccessful";
OleDbCommand Comm = new OleDbCommand();
Comm.Connection = Conn;
Comm.CommandText = "Select * FROM Plants;";
OleDbDataAdapter DA = new OleDbDataAdapter();
DA.SelectCommand = Comm;
DataSet DS = new DataSet();
OleDbCommandBuilder CB = new OleDbCommandBuilder(DA);
DA.Fill(DS, "PLANTS");
}
catch (Exception e)
{
Response.Redirect("Error.aspx");
}
finally
{
Conn.Close();
Conn.Dispose();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindDataPlant();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
BindDataPlant();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int PlantID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox txtLatinName = (TextBox)row.FindControl("txtLatinName");
TextBox txtPopularName = (TextBox)row.FindControl("txtPopularName");
TextBox txtSeason = (TextBox)row.FindControl("txtSeason");
TextBox txtAftercare = (TextBox)row.FindControl("txtAftercare");
TextBox txtCategories = (TextBox)row.FindControl("txtCategories");
TextBox txtDescription = (TextBox)row.FindControl("txtDescription");
TextBox txtUses = (TextBox)row.FindControl("txtUses");
TextBox txtFoliageColour = (TextBox)row.FindControl("txtFoliageColour");
TextBox txtFlowerColour = (TextBox)row.FindControl("txtFlowerColour");
TextBox txtFloweringPeriod = (TextBox)row.FindControl("txtFloweringPeriod");
TextBox txtHeight = (TextBox)row.FindControl("txtHeight");
TextBox txtSpread = (TextBox)row.FindControl("txtSpread");
TextBox txtInstructions = (TextBox)row.FindControl("txtInstructions");
TextBox txtPrice = (TextBox)row.FindControl("txtPrice");
OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("~/App_Data/LincolnGardenCentre.accdb;"));
try
{
Conn.Open();
if (Conn.State.ToString() == "Open")
Page.Title = "Connection Successful";
else
Page.Title = "Connection Unsuccessful";
OleDbCommand Comm = new OleDbCommand();
Comm.Connection = Conn;
Comm.Parameters.Add("#PlantID", OleDbType.Integer).Value = PlantID.ToString();
Comm.Parameters.Add("#LatinName", OleDbType.VarChar).Value = txtLatinName.Text;
Comm.Parameters.Add("#PopularName", OleDbType.VarChar).Value = txtPopularName.Text;
Comm.Parameters.Add("#Season", OleDbType.VarChar).Value = txtSeason.Text;
Comm.Parameters.Add("#Aftercare", OleDbType.VarChar).Value = txtAftercare.Text;
Comm.Parameters.Add("#Categories", OleDbType.VarChar).Value = txtCategories.Text;
Comm.Parameters.Add("#Description", OleDbType.VarChar).Value = txtDescription.Text;
Comm.Parameters.Add("#Uses", OleDbType.VarChar).Value = txtUses.Text;
Comm.Parameters.Add("#FoliageColour", OleDbType.VarChar).Value = txtFoliageColour.Text;
Comm.Parameters.Add("#FlowerColour", OleDbType.VarChar).Value = txtFlowerColour.Text;
Comm.Parameters.Add("#FloweringPeriod", OleDbType.VarChar).Value = txtFloweringPeriod.Text;
Comm.Parameters.Add("#Height", OleDbType.VarChar).Value = txtHeight.Text;
Comm.Parameters.Add("#Spread", OleDbType.VarChar).Value = txtSpread.Text;
Comm.Parameters.Add("#Instructions", OleDbType.VarChar).Value = txtInstructions.Text;
Comm.Parameters.Add("#Price", OleDbType.Decimal).Value = txtPrice.Text;
Comm.CommandText = "UPDATE Plants SET LatinName = #LatinName, PopularName = #PopularName, Season = #Season, Aftercare = #Aftercare, Categories = #Categories, Description = #Description, Uses = #Uses, FoliageColour = #FoliageColour, FlowerColour = #FlowerColour, FloweringPeriod = #FloweringPeriod, Height = #Height, Spread = #Spread, Instructions = #Instructions, Price = #Price WHERE PlantID = #PlantID";
Comm.Connection = Conn;
Comm.ExecuteNonQuery();
GridView1.EditIndex = -1;
BindDataPlant();
}
catch (Exception ex)
{
Response.Redirect("Error.aspx");
}
finally
{
Conn.Close();
Conn.Dispose();
}
}
}
Can anyone shed any light onto what is happening here?
Thanks
Remove DataSourceId in grid's markup and bind grid in BindDataPlant method
GridView1.DataSource = DS;
GridView1.DataBind()
After statement DA.Fill(DS, "PLANTS");
It will solve your problem.