I had a basicSearch page working perfectly with the keyword searching (highlighting the keyword on the search result page) but when I modified it to work with a querystring, it's displaying ALL the records with the keyword highlighted.
aspx page:
<form id="form1" runat="server">
<div id="mainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript">
function updated() {
// close the popup
tb_remove();
// refresh the update panel so we can view the changes
$('#<%= me.btnRefreshResources.ClientID %>').click();
}
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
// reapply the thick box stuff
tb_init('a.thickbox');
}
}
</script>
<asp:AccessDataSource ID="AccessDataSource" runat="server"
DataFile="~/Dir/search.mdb"
SelectCommand="SELECT * FROM [searches] ORDER BY [Title]"
FilterExpression="Title like '%{0}%' or LastName like '%{1}%' or FirstName like '%{2}%' or Description like '%{3}%' ">
<FilterParameters>
<asp:ControlParameter Name="Title" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="LastName" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="FirstName" ControlID="txtSearch" PropertyName="Text" />
<asp:ControlParameter Name="Description" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:AccessDataSource>
<div id="basicSearch" align="left">
<b style="font-family: Arial, Helvetica, sans-serif; font-size: 18px">Enter a keyword: </b><asp:TextBox ID="txtSearch" runat="server" Width="300px" Font-Size="18px" />
<asp:Button ID="btnBasicSearch" Text="Search" Runat="Server"/>
<asp:Button ID="btnBasicClear" Text="Clear" Runat="Server"/><br /><br />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnRefreshResources" runat="server" style="display:none" OnClick="Refresh_Click" />
<asp:GridView ID="gvResources" runat="server" DataSourceID="AccessDataSource" CssClass="datagrid" GridLines="None" AutoGenerateColumns="false" AllowSorting="True" PageSize="50" AllowPaging="True" Width="100%" OnPageIndexChanging="gvResources_PageIndexChanging"> <PagerSettings Position="TopAndBottom" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Type" HeaderStyle-HorizontalAlign="Right" SortExpression="Title">
<ItemTemplate>
<%# DisplayType(Eval("Book"))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label ID="lblTitle" Text='<%# HighlightText(Eval("Title").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" Text='<%# HighlightText(Eval("Description").ToString()) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<a id="btnShowPopup" runat="server" class="thickbox" title='<%# Eval("ID", "Request Resource ID: {0}") %>' href='<%# Eval("ID", "RequestResource.aspx?ID={0}&TB_iframe=true&height=350&width=500&modal=true") %>'>Request This Item</a> </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code behind:
Partial Class BasicSearch
Inherits System.Web.UI.Page
Dim SearchString As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SearchString = Request.QueryString("Keyword")
End Sub
Protected Sub Refresh_Click(ByVal sender As Object, ByVal args As EventArgs)
' update the grids contents
Me.gvResources.DataBind()
End Sub
Function HighlightText(ByVal InputTxt As String) As String
If SearchString = "" Then
Return InputTxt
Else
Dim ResultStr As Regex
ResultStr = New Regex(SearchString.Replace(" ", "|"), RegexOptions.IgnoreCase)
Return ResultStr.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceWords))
End If
End Function
Public Function ReplaceWords(ByVal m As Match) As String
Return "<span class=highlight>" + m.ToString + "</span>"
End Function
Protected Sub gvResources_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvResources.PageIndex = e.NewPageIndex
SearchString = txtSearch.Text
gvResources.DataBind()
End Sub
Protected Sub btnBasicSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBasicSearch.Click
SearchString = txtSearch.Text
Response.Redirect("BasicSearch.aspx?Keyword=" & SearchString)
End Sub
Protected Sub btnBasicClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBasicClear.Click
txtSearch.Text = ""
SearchString = ""
End Sub
Protected Function DisplayType(ByVal Book As Boolean) As String
If Book Then
Return "Book"
Else
Return "Other"
End If
End Function
End Class
Just a guess - what is the value of SearchString when the HighlightText function is executing? You are storing the querystring in a local page variable, which only exists while the page request is executing.
If HighlightText gets called without Page_Load being called (in the same request), SearchString will be empty.
Related
I'm using asp.net web form gridview and I run into a problem when inserting a new record from footer.
my footer has the different input that should be submitted but when I submit the record they change.
for example, I have an input fname if I type the name "Issa" I get it like this ",Issa"
the "," character is being added and I don't know why
this is how I retrieve the record.
Dim fname As String = TryCast(staffs_gridvw.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
and this is how my templet field looks like.
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("sfname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("sfname") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
any suggestion on how can I fix this issue???
Hum, I am un-able to re-produce this error.
My markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" />
My code to fill:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid
End If
End Sub
Sub LoadGrid()
Dim rstData As DataTable
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName")
GridView1.DataSource = rstData
GridView1.DataBind()
End Sub
We now get this:
So I type in hello world into that text box, hit the button, with this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fname As String = TryCast(GridView1.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
Debug.Print(fname)
End Sub
And I see this:
So, I guess the question is what other operations are you doing to that GV?
Edit: Button is also in the the GV footer
Ok, so then we have this:
<div style="padding:25px;width:20%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true" CssClass="table">
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="sfname_txtbox" CssClass="form-control" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="footer_sfname_txtbox" CssClass="form-control" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hotel">
<ItemTemplate>
<asp:Label ID="lblHotel" runat="server" Text='<%#Eval("HotelName") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And code to load - same as before.
So, now we see this:
Of course, the button is now in the GV - so I can't double click to wire up a event, but you of course then use markup.
Type in onclick= (hit ctrl-space bar under the quotes) - and then you get this option:
Ok, so now we have our event behind.
This code:
Protected Sub Button2_Click(sender As Object, e As EventArgs)
Dim fname As String = TryCast(GridView1.FooterRow.FindControl("footer_sfname_txtbox"), TextBox).Text.Trim
Debug.Print(fname)
End Sub
And now this:
And click on button, I see/get this:
struggling since morning. the scenario is as follow:
I have a ASP.NET web page having
two dropdownlist
two buttons
One GridView
Wants to fill gridview based on dropdownlist selected value
here is the .aspx code
<%# Page Title="" Language="VB" MasterPageFile="~/Admin/ADMIN.master" AutoEventWireup="false" CodeFile="EditSTUdetail.aspx.vb" Inherits="Admin_EditSTUdetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<style type="text/css">
.auto-style1
{
height: 42px;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div align="center">
<fieldset>
<legend style="font-size: 16px;">SEARCH / EDIT / DELETE STUDENT RECORDS
</legend>
<div style="overflow: auto">
<div>
<asp:Label ID="lblMsg" runat="server" CssClass="lblresponse" />
<table style="margin: 3px auto 1px auto; height: 72px;">
<tr>
<td style="text-align: right;" class="auto-style2">Select Session/सत्र का चयन करें :
</td>
<td class="auto-style3">
<asp:DropDownList ID="ddlSession" runat="server" AppendDataBoundItems="True" Width="236px" Height="28px">
<asp:ListItem Text="--Select Session--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="ddlSession" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="text-align: right;" class="auto-style1">Select Course /कक्षा का चयन करें :
</td>
<td>
<asp:DropDownList ID="ddlCourse" runat="server" AppendDataBoundItems="true" Width="236px" Height="28px">
<asp:ListItem Text="--Select Course--" Value=""></asp:ListItem>
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="ddlCourse" ForeColor="#990000"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td class="auto-style1"></td>
<td class="auto-style1">
<asp:Button ID="btnSearch" runat="server" Text="SEARCH" CssClass="button" OnClick="btnSearch_Click" Height="34px" Width="77px" /></td>
<td colspan="2" class="auto-style1">
<asp:Button ID="btnRefresh" runat="server" Text="REFRESH" CssClass="button" OnClick="btnRefresh_Click" Height="34px" Width="77px" /></td>
</tr>
</table>
</div>
</div>
<asp:GridView ID="GVdata" runat="server" Width="674px" CaptionAlign="Top"
AutoGenerateColumns="False" Height="100px" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" GridLines="Vertical"
EmptyDataText="There Are No Record Found" OnRowCancelingEdit="gvManageOrders_RowCancelingEdit"
OnRowDeleting="gvManageOrders_RowDeleting" OnRowEditing="gvManageOrders_RowEditing"
OnRowUpdating="gvManageOrders_RowUpdating">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Sr. No." ItemStyle-Width="20">
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit/Remove" ShowDeleteButton="True"
ShowEditButton="True" DeleteText="Remove" />
<asp:TemplateField HeaderText="Student ID" Visible="True">
<ItemTemplate>
<asp:Label ID="studentID" runat="server" Text='<%# Bind("studentID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Sname" runat="server" Text='<%# Bind("Sname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Father's Name" Visible="True">
<ItemTemplate>
<asp:Label ID="Fname" runat="server" Text='<%# Bind("Fname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle BackColor="#eeeeee" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px" Font-Size="Large" ForeColor="#851010"
HorizontalAlign="Center" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#851010" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#851010" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</fieldset>
</div>
</asp:Content>
and here is my vb code:
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Net.Mail
Imports System.Data
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Partial Public Class Admin_EditSTUdetail
Inherits System.Web.UI.Page
Private myds As DataSet
Protected Sub LoadSession()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("select sessionID, session from tblcategories ORDER by session DESC", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlSession.DataTextField = ds.Tables(0).Columns("session").ToString()
' text field name of table dispalyed in dropdown
ddlSession.DataValueField = ds.Tables(0).Columns("sessionID").ToString()
' to retrive specific textfield name
ddlSession.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlSession.DataBind()
ddlSession.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub LoadCourse()
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
con.Open()
Dim com As New SqlCommand("SELECT DISTINCT course AS mycolumn FROM " _
& " tblsubjects where course is not null and " _
& "not course = '' order by mycolumn", con)
Dim da As New SqlDataAdapter(com)
Dim ds As New DataSet()
da.Fill(ds)
ddlCourse.DataTextField = ds.Tables(0).Columns("mycolumn").ToString()
' text field name of table dispalyed in dropdown
ddlCourse.DataValueField = ds.Tables(0).Columns("mycolumn").ToString()
' to retrive specific textfield name
ddlCourse.DataSource = ds.Tables(0)
'assigning datasource to the dropdownlist
ddlCourse.DataBind()
ddlCourse.SelectedIndex = -1
'binding dropdownlist
End Sub
Protected Sub fillgrid()
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("cmsDB").ConnectionString)
Dim cmd As New SqlCommand("SELECT StudentID,session,course,Sname,Fname FROM [tblstudetail] WHERE " _
& " [session] = '" + ddlSession.SelectedValue.ToString() + "' AND " _
& " [course] = '" + ddlCourse.SelectedValue.ToString() + "'", cn)
cn.Open()
Dim da As New SqlDataAdapter(cmd)
myds = New DataSet()
da.Fill(myds)
GVdata.DataSource = myds
GVdata.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
LoadSession()
LoadCourse()
fillgrid()
End If
End Sub
Protected Sub gvManageOrders_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowEditing(sender As Object, e As GridViewEditEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub gvManageOrders_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
Throw New NotImplementedException
End Sub
Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If Not Page.IsPostBack Then
fillgrid()
End If
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
GVdata.DataSource = Nothing
End Sub
End Class
But it is not returning what i request.
Kindly HELP me out this....
PLease remove these lines ,
ddlSession.SelectedIndex = -1
ddlCourse.SelectedIndex = -1
from the end of the LoadCourse and LoadSession methods. These are resetting the dropdown values and causing issue.
The flow is messed up in your code. You are calling loadsession , loadcourses and fillgrid serially from the page load method. Think about it. When the code in fillgrid executes there is no selected value in the drop downs. Obviously no data is found and so the gridview is not visible.
The better way to handle is introduce two new methods like this,
Protected Sub ddlCourses_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlSession.SelectedIndexChanged
and
Protected Sub ddlAC3_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlCourse.SelectedIndexChanged
Inside these methods send out a call to fillgrid.
Also inside the fillgrid method first validate there is some value in both the ddlCourse and ddlSession dropdowns , then send out the database command.
First of all
ddlSession.SelectedValue.ToString()
become
ddlSession.SelectedValue
Then in Protected Sub btnSearch_Click remove
If Not Page.IsPostBack Then
Then
ddlCourse.SelectedIndex = -1
become
ddlCourse.ClearSelection();
Finally, are you sure there aren't NULL value in the database?
Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.
This is my datalist:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("ID") %>' Visible="False" />
Titre:
<asp:Label ID="TitreLabel" runat="server" Text='<%# Eval("Titre") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' />
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}") %>' Width="200" Height="200"/>
<br />
comments:
<asp:Label ID="commentsLabel" runat="server" Text='<%# Eval("comments") %>' />
<br />
Ajouter commentaire
<asp:button ID="btnAjouter" runat="server" OnCommand="Button_Command"
CommandName="add" Text="Ajouter" />
<asp:TextBox ID="TextBoxComments" runat="server"></asp:TextBox>
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
This my aspx.vb button event:
Sub Button_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("updateComments", con)
cmd.CommandType = CommandType.StoredProcedure
//I try this ....
cmd.Parameters.Add("#id", SqlDbType.Int).Value = DataList1.FindControl("IdLabel").ToString()
cmd.Parameters.Add("#Comments", SqlDbType.NVarChar).Value = DataList1.FindControl("TextBoxComments").ToString()
cmd.ExecuteNonQuery()
End Sub
I get an error like this: "The object reference is not definied to an object instance"
How can I catch the value from the label IdLabel and TextBoxComments in this situation?
You should handle the DataList's ItemCommand instead of the Button's Command.
Then you can find your controls with e.Item.FindControl:
Private Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
If e.CommandName = "add" Then
Dim IdLabel = DirectCast(e.Item.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(e.Item.FindControl("TextBoxComments"), TextBox)
' ... '
End If
End Sub
on aspx, remove your redundant Command-handler:
<asp:button ID="btnAjouter" CommandName="add" Text="Ajouter" runat="server" />
If you want to use the Button's Click-Event instead, that's possible also.
Protected Sub btnAjouter_Click(sender As Object, e As EventArgs)
Dim container = DirectCast(DirectCast(sender, Control).NamingContainer, DataListItem)
Dim IdLabel = DirectCast(container.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(container.FindControl("TextBoxComments"), TextBox)
' ... '
End Sub
on aspx, add the click-event handler to the button:
<asp:button ID="btnAjouter" OnClick="btnAjouter_Click" Text="Ajouter" runat="server" />
After editing some fields, clicking on Update doesn't show the new values. I have tried two ways to retrieve the new values as you can see from this shortened version of the ItemUpdating event (and both return the old ones) :-
Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdating
Dim txtPassword As TextBox = CType(DetailsView1.Rows(1).Cells(1).FindControl("txtPassword"), TextBox)
Struct_Student.password = txtPassword.Text
Dim PasswordValue As String = e.NewValues("password").ToString()
Struct_Student.password = PasswordValue
End Sub
Here is a shortened version of the aspx :-
<asp:Content ID="Content1" ContentPlaceHolderID="cpMainContent" Runat="Server">
<div id="Controls">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DetailsView ID="DetailsView1"
runat="server"
AutoGenerateRows="False"
DataKeyNames="student_id" DataSourceID="SqlDataSource1"
ForeColor="Blue"
BackColor="#FFF7E6"
AutoPostBack="True"
AutoGenerateEditButton = True
AutoGenerateInsertButton = True
OnModeChanging="StudentDetailView_ModeChanging"
Height=163px
Width=327px
style="left: 400px; top: 1px; position: absolute;">
<Fields>
<asp:TemplateField
HeaderText="Password">
<EditItemTemplate>
<asp:TextBox
id="txtPassword"
Text = '<%# Bind ("password") %>'
runat = "server" />
<asp:RequiredFieldValidator
ID = "reqPassword"
ControlToValidate = "txtPassword"
Text = "(required)"
Display = "Dynamic"
runat = "server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label
id="PasswordLabel"
runat="server"
Text = '<%# Eval("password") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField
datafield="emailaddress"
headertext="Email address"
SortExpression="emailaddress"
/>
</Fields>
</asp:DetailsView>
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:FCLManager %>" ProviderName="MySql.Data.MySqlClient"
SelectCommand="Select * from tblstudentinfo WHERE centre_id = #CentreID and fullname = #FullName"
<SelectParameters>
<asp:Parameter Name="CentreID" Type="Int16" DefaultValue="0" />
<asp:Parameter Name="FullName" Type="String" DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</div> <%--Controls div--%>
</asp:Content>