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.
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 have a gridview and detailsview in my aspx page and using object data source to display data, the primary key on the table is consist of 2 columns, so I set DataKeyNames = "ID,StepCount" in Gridview1, see my web page code below:
<asp:GridView ID="GridView1" DataKeyNames="ID,StepCount" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="StepCount" HeaderText="StepCount" SortExpression="StepCount" />
<asp:BoundField DataField="Direction" HeaderText="Direction" SortExpression="Direction" />
<asp:BoundField DataField="StatusChangeTo" HeaderText="StatusChangeTo" SortExpression="StatusChangeTo" />
</Columns>
</asp:GridView>
<br />
<asp:DetailsView ID="DetailsView1" DataKeyNames="ID,StepCount" runat="server" Height="50px" Width="125px" AutoGenerateRows="False"
DataSourceID="ObjectDataSource2">
<Fields>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="StepCount" HeaderText="StepCount" SortExpression="StepCount" />
<asp:BoundField DataField="Direction" HeaderText="Direction" SortExpression="Direction" />
<asp:BoundField DataField="StatusChangeTo" HeaderText="StatusChangeTo" SortExpression="StatusChangeTo" />
<asp:BoundField DataField="TicketID" HeaderText="TicketID" SortExpression="TicketID" />
<asp:BoundField DataField="StandaloneIncident" HeaderText="StandaloneIncident" SortExpression="StandaloneIncident" />
<asp:BoundField DataField="CETransactionXML" HeaderText="CETransactionXML" SortExpression="CETransactionXML" />
</Fields>
</asp:DetailsView>
<br />
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="getAllMastterChildren"
TypeName="HarnessMaintain.Pages.DataAccessLayer"></asp:ObjectDataSource>
<br />
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="getMasterchildByPK"
TypeName="HarnessMaintain.Pages.DataAccessLayer">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="ID" PropertyName="SelectedValue"
Type="Int32" />
<asp:ControlParameter ControlID="GridView1" Name="StepCount" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
following is my C# code to retrieve data according to choosed id and stepcount from Gridview:
public static List<MasterChildDetail> getMasterchildByPK(int ID, int StepCount)
{
string sqlStr = "select * from mswscemasterchild where id = :id and step_count = :step_count";
List<MasterChildDetail> mcds = new List<MasterChildDetail>();
MasterChildDetail mcd = new MasterChildDetail();
using (OracleConnection ocon = new OracleConnection(conStr))
{
OracleCommand ocmd = new OracleCommand(sqlStr, ocon);
ocmd.Parameters.Add(":id", ID);
ocmd.Parameters.Add(":step_count", StepCount);
ocmd.Connection.Open();
OracleDataReader reader = ocmd.ExecuteReader();
while (reader.Read())
{
mcd.ID = Convert.ToInt32(reader["ID"]);
mcd.StepCount = Convert.ToInt32(reader["STEP_COUNT"]);
if (System.DBNull.Value.Equals(reader["DIRECTION"]))
{
mcd.Direction = null;
}
else
{
mcd.Direction = reader["DIRECTION"].ToString();
}
if (System.DBNull.Value.Equals(reader["STATUS_CHANGE_TO"]))
{
mcd.StatusChangeTo = null;
}
else
{
mcd.StatusChangeTo = reader["STATUS_CHANGE_TO"].ToString();
}
if (System.DBNull.Value.Equals(reader["TICKET_ID"]))
{
mcd.TicketID = null;
}
else
{
mcd.TicketID = reader["TICKET_ID"].ToString();
}
if (System.DBNull.Value.Equals(reader["STANDALONE_INCIDENT"]))
{
mcd.StandaloneIncident = null;
}
else
{
mcd.StandaloneIncident = reader["STANDALONE_INCIDENT"].ToString();
}
if (System.DBNull.Value.Equals(reader["CE_TRANSACTION_XML"]))
{
mcd.CETransactionXML = null;
}
else
{
mcd.CETransactionXML = reader["CE_TRANSACTION_XML"].ToString();
}
mcds.Add(mcd);
break;
}
}
return mcds;
}
by debugging, I found a wired issue, the value of passed ID and StepCount are always exactly the same, even though I click on the second "Select" and the third "Select", see below:
can you tell me why or how to fix this issue?
The primary key column of your database is your DataKey name. And you can't have 2 primary keys in 1 table. So there should be only 1 column in GridView's DataKey name.
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
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();
}
}
}
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.