Quantcast
Channel: DataSource Controls - SqlDataSource, ObjectDataSource, etc.
Viewing all 956 articles
Browse latest View live

Bind Dropdownlist

$
0
0

Hi

I need to fill a Dropdownlist from one SQLDataSource , and Bind the selectedvalue to another SQLDataSource

Note:

the dropdownlist and the (filling) sqldatasource locates in the edit template of a detailsview

is there any way to do this?

thank you


ObjectDataSource and FormView: How to manually load/save values?

$
0
0

Hello,


I have an ObjectDataSource and a FormView. When I edit a record, all the fields are loaded automatically and also saved automatically, when the user clicks the insert/update button.

However, there is one attribute that is stored in a different table, and I would like to handle it in the same form.

Of course, I could join the tables with a query, but to make it updatable, I would have to create instead of triggers. I would like to avoid this for this one attribute.

For me it would be sufficient, if I could have an unbound field in my form which I load and save manually. But how would this be done?
Which are the event handlers where I should load it and where I should save it? And within these handlers, how can I easily access the database (i. e. without explicitely creating and opening/closing a connection)?

Thanks
Magnus

DataSet Designer doesn't create INSERT/UPDATE/DELETE-Commands for View

$
0
0

Hello,

I want to create a TableAdapter for a view. Unfortunately, the DataSet designer doesn't create INSERT/UPDATE/DELETE commands for it. I assume it's because it's a view.

However, the view has INSTEAD of triggers and can be handled like a table.

What can I do to have the designer generate the commands?

Thanks
Magnus

Why can’t any references to my SQL database be found?

$
0
0

Errors occur everywhere there is an attempt to access a database table, such as with “TextTable texttable = db.TextTables.SingleOrDefault(p => p.TexID == TextID);” which state: Error 16 'System.Data.Linq.Table<TransLangTable>' does not contain a definition for 'SingleOrDefault'.  Errors also occur whenever there is an attempt to access the database directly such as with “SqlConnection conn = null;” which state: Error 52 The type or namespace name 'SqlConnection' could not be found.

 

Obviously, I included a “using System.Data.SqlClient;” statement in the code section along with many others.  There is also a statement of: “<add name="ENCdbConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ENCdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/> within the connectionStrings portion of the web.config file.  In addition, there is, “string ENCconn = ConfigurationManager.ConnectionStrings["ENCdbConnectionString"].ToString();” at the start of the script portion of the code.

 

I believe that the problem is due to the fact that I only copied the database and DataClasses from another website into my current website instead of creating them directly.  For some reason, the Debug function cannot relate to any of my code that relates to the database.  I even attempted to copy the code into a new web page file within the other website where all other web pages work fine with the database.  However, I obtained the exact same results with this file when I attempted to run it.  What am I doing wrong?  Please help.

 

Maurice

asp:SqlDataSource delete command needs to have two sql statements to delete from two tables, but it only executes the first statement.

$
0
0

In the following code, you will see that the delete command has two statements.

delete FROM gdsvalue.usersitesqueue where userid = (select iduserprofile from gdsvalue.userprofile where iduserprofile = ?);

delete FROM gdsvalue.userprofile where iduserprofile = ?

Only the first statement is executed and it does not execute the 2nd statement. No error is thrown.

Please guide me, how to make this work ?

The complete sqldatasource code is shown below.

<asp:SqlDataSource ID="SqlDataSourceEditUsers" runat="server" ConflictDetection="CompareAllValues"

ConnectionString="<%$ ConnectionStrings:SVMySQLConnectionString %>"
DeleteCommand="delete FROM gdsvalue.usersitesqueue where userid = (select iduserprofile from gdsvalue.userprofile where iduserprofile = ?);
delete FROM gdsvalue.userprofile where iduserprofile = ?"
InsertCommand="INSERT INTO [userprofile] ([iduserprofile], [ldapusername], [worklocationdir], [group], [domain]) VALUES (?, ?, ?, ?, ?)"
OldValuesParameterFormatString="original_{0}" ProviderName="<%$ ConnectionStrings:SVMySQLConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM [userprofile]" UpdateCommand="UPDATE [userprofile] SET [ldapusername] = ?, [worklocationdir] = ?, [group] = ? WHERE [iduserprofile] = ? AND (([ldapusername] = ?) OR ([ldapusername] IS NULL AND ? IS NULL)) AND (([worklocationdir] = ?) OR ([worklocationdir] IS NULL AND ? IS NULL)) AND (([group] = ?) OR ([group] IS NULL AND ? IS NULL))">
<DeleteParameters>
<asp:Parameter Name="original_iduserprofile" Type="Int32" />
<asp:Parameter Name="original_ldapusername" Type="String" />
<asp:Parameter Name="original_ldapusername1" Type="String" />
<asp:Parameter Name="original_worklocationdir" Type="String" />
<asp:Parameter Name="original_worklocationdir1" Type="String" />
<asp:Parameter Name="original_group" Type="String" />
<asp:Parameter Name="original_group1" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="iduserprofile" Type="Int32" />
<asp:Parameter Name="ldapusername" Type="String" />
<asp:Parameter Name="worklocationdir" Type="String" />
<asp:Parameter Name="group" Type="String" />
<asp:Parameter Name="domain" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="ldapusername" Type="String" />
<asp:Parameter Name="worklocationdir" Type="String" />
<asp:Parameter Name="group" Type="String" />
<asp:Parameter Name="original_iduserprofile" Type="Int32" />
<asp:Parameter Name="original_ldapusername" Type="String" />
<asp:Parameter Name="original_ldapusername1" Type="String" />
<asp:Parameter Name="original_worklocationdir" Type="String" />
<asp:Parameter Name="original_worklocationdir1" Type="String" />
<asp:Parameter Name="original_group" Type="String" />
<asp:Parameter Name="original_group1" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>

Filter Text starts with Numbers

$
0
0

Hi,

How to assign dataview rowfilter to sqldatasource filterexpression , which needs to show the list of text starts with numbers (sql query like'[0-9]%')

Thx

CS

DropDownList.DataBind() aborts when SqlDataSource.SelectParameters[...].DefaultValue is null

$
0
0

Hi,

I have a SQLDataSource representing a list of cars (fictive) with one parameter:

<asp:SqlDataSource ID="src_Cars" runat="server"
    ConnectionString='<%$ ConnectionStrings:MyConnectionString %>'
    SelectCommand="SELECT num FROM [cars] WHERE (num NOT IN (SELECT numFROM cars_sold WHERE (num IS NOT NULL)) OR num=@special);"<SelectParameters><asp:Parameter Name="special" DbType="String" ConvertEmptyStringToNull="true"></asp:Parameter></SelectParameters></asp:SqlDataSource>

I set the parameter like this:

private void setNum(String num)
{
   src_Cars.CancelSelectOnNullParameter = false;
   src_Cars.SelectParameters["num"].ConvertEmptyStringToNull = true;
   src_CarsSelectParameters["own"].DefaultValue = num;
   src_Cars.DataBind();
}

Then, I bind a DropDownList to the DataSource:

DwopDownList lst;
lst.DataSource = src_Cars;
lst.DataBind();

When num is not null, the list is filled as expected.

When num is null, the list does not get filled. But attention: The list is not "filled" with an empty list. Instead the DataBind method must abort somehow.
Here is why: The user may select from different categories: cars and bikes. When he selects the bikes category, the DropDownList is filled with bikes.
When he then selects the cars category again, the list remains filled with bikes, even after DataBind is called!

Therefore, I assume that the data binding process must be abort somewhere.

When I copy the SQL string in SQL Management Studio and replace "@special" with "NULL", it works perfectly.

What can be the problem here?

Thanks
Magnus

Sorting with ObjectDataSource and Report

$
0
0

I have seen examples online on sorting ObjectDataSource with GridView, but I have not been able to make it work with a Report because there is a DataSet, TableAdapter, etc.

I would like to use exactly the same report with exactly the same data but sort depending on user request.

Help is most appreciated.


Showing a gridview within a listview

$
0
0

Hi,

I must apologise if this seems a stupid question, but I have only just started with asp.net

I have two tables

  1. History with PSID, Surname, Week as fields
  2. TSHistory with TSID, PSID, Date, Hours as fields

Primary keys are in bold and foreign keys are bold/italic

I have created an aspx page to show 'History' as a listview, which brings up the data but the 'TSHistory' gridview shows all data not just the few rows which have the same PSID.

I have tried filters, datakeynames, controlparameters and a host of others which I can't recall, but I can't seem to get it work. I can use two gridviews and get the information to appear in the 2nd gridview but I need to show all data in 'History' every time I view the page, hence the listview.

Please help, it's driving me insane :)

Thank you

SelectCommand for NULL

$
0
0

I have a GridView that is populated with a SqldataSource Select Command, as illustrated below. When there is a "Null" value in a table cell (e.g. UA.Section) ... Then no results are displayed in the resulting display and the emptydatarowstyle message displays.

I am not sure if there is something to do, either in the SQL or does this type of issue need to be addressed by the bound field... and how?

Thank you...

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
      ConnectionString="<%$ ConnectionStrings:connString %>"                         

       SelectCommand="SELECT 
                             UA.[UserID],
                             UA.[UserName],
                             UA.[UserLastName],	
                             UA.[TempPassword],
                             UA.[Initials],
                             UA.[Shared1],			
                             UA.[Shared2],				
                             UA.[AddDate],	
                             UA.[Email],				
                             UA.[Laboratory],			
                             UA.[Section],	
                             UA.[Location],
                             UA.[UserLastName],		
                             UA.[Section],	                            
                             SL.[Description],		
                             SEC.[SectionDecode],
                             CTL.[Description] AS LABSECT
                        FROM [DIS_PHLINVENTORY].[dbo].[t_UserAccount] AS UA
                        Inner Join t_ScanLocations AS SL ON UA.Location=SL.DescriptionID
                        Inner Join ICDbS_ddl_PHLSections AS SEC ON UA.Section=SEC.SectionCode
                        Inner Join ClinicalTestLab AS CTL ON UA.Laboratory=CTL.LabID
                        WHERE [UserName] = @UserName"><SelectParameters><asp:QueryStringParameter Name="UserName" QueryStringField="UserID" /></SelectParameters>

SqlDataSource and setting ControlParameters

$
0
0

Hi. I'm not a web developer. I'm a data warehouse dev but I've had this task dumped on me. My experience of asp.net and c# is very basic.

I've got a data list view which is populated by a sql command and i'm trying to add a parameter so users can filter the list.

I've managed to get the connection to the stored proc in sql but it refuses to recognise the parameter.

Here's some code:

The input box is defined like this

<asp:TextBox ID="txtSearch" runat="server" Text="" />

and then i've got this on the same page

<asp:SqlDataSource 
            ID="SqlDataSource1" 
            runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnTechnicalForms %>" 
            SelectCommand="usp_SearchPI"><SelectParameters><asp:ControlParameter ControlID="txtSearch" PropertyName="Text" DBType="String" DefaultValue="" Name="SearchTerm"  /></SelectParameters></asp:SqlDataSource>

The message I'm getting back is:

Procedure or function 'usp_SearchPI' expects parameter '@SearchTerm', which was not supplied

My stored proc has just one parameter, @SearchTerm which is a varchar(100).

Th proc is working but the parameter isn't being passed. Can anybody help please?

Thanks,

Nick

Export SqlDataSource to excel

$
0
0

Hi,

I want export all data of SqlDataSource to excel,

How i do?

Help me, Please

SQL Server Stored Procedure

$
0
0

I have the following VB.net code and would appreciate if some one help to do same in STORED PROCEDURE.

.---------------------------

Dim myConnString As String = "server=.\sqlexpress;database=TEST;uid=sa;pwd=abcd"

Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(myConnString)

Dim tyear As String = DropDownList2.SelectedItem.Text.Replace("'", "''")
Dim tmonth As String = DropDownList1.SelectedItem.Text.Replace("'", "''")
Dim emp1 As String = TextBox1.Text.Replace("'", "''")

Dim ltmon As String, ltyear As String

Dim mySelectQuery As String = "Select * from LogRun WHERE tyear = '" & tyear & "' AND tmonth = '" & tmonth & "' AND empno = '" & emp1 & "' order by TDate,TimeIn"

Dim myConnection As New SqlConnection(myConnString)
Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
myConnection.Open()

Dim lempno As String, lttdate As Date

Dim myReader As SqlDataReader
myReader = myCommand.ExecuteReader()
While myReader.Read()

lempno = myReader("empno")
lttdate = myReader("tdate")

Dim queryString As String = "DELETE from Absent where empno = '" & lempno & "' and tdate = '" & lttdate & "' "

Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim rowsAffected As Integer = 0
dbConnection.Open()
rowsAffected = dbCommand.ExecuteNonQuery
dbConnection.Close()

End While
myReader.Close()
myConnection.Close()

--------------------------------------

then call fro vb.net

Thanks

Pass session variable as parameter

$
0
0

Hello Every body

my page contains a GridView that is bounded to SQLDataSource

this is the SelectQuery

SELECT Activity.ID,Activity.title 
FROM   Activity 
WHERE Activity.Department=(SELECT Department.ID 
                           FROM Department 
                           WHERE Department.Head=(SELECT Employee.ID 
                                                  FROM Employee 
                                                  WHERE UserId=@UI))

this query works fine if I test it and returns the right records

in the page_load event handler , it reads the current logged in user id and stores it in a session variable

this is the code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim user_id As Guid = Membership.GetUser().ProviderUserKey
        Session("UI") = user_id.ToString

End Sub


I configured the SQLDataSource to read the parameter from this session variable

see image below

But , 

I dont know where is the mistake , 

the grid do not show the targeted records

Any Help is appreciated

thank you

Update Distinct

$
0
0

I have a table that has an ReviewNum, Facility, Area and SubArea.

ReviewNum     Facility     Area     SubArea

1                        PD            301        ME

2                        PD            301        MW

44                      PD            301        MW

55                      PD            301        ME

44                      PD            301        ME

66                      PD            301        MC

2                        PD            301        MC

What I need to do is select the Distinct ReveiwNum of all facility area and subarea of PD facility, 301 Area and SubArea ME,MC and MW then change all the SubAreas to SPROG.

So I would end up with:

ReviewNum     Facility     Area     SubArea

1                        PD            301        SPROG

2                        PD            301        SPROG

44                      PD            301        SPROG

55                      PD            301        SPROG

66                      PD            301        SPROG

I got the select part:

select distinct ReviewNum from FacilityUse
Where Facility = 'PD' and Area = '301' and (SubArea = 'MC' or SubArea = 'ME' OR SubArea = 'MW')

But I can't figure the rest.

Please help

Thanks


Listview label into a session variable

$
0
0

Hi,

After having my previous problem solved here I thought I would again turn to this site for help.

It seems such a simple event, but I can't get it to work correctly. To aid with security I've changed all the names, but the idea is still the same.

I have a aspx wep page that has a label (idlabel). As per my code it currently reads "Nothing".

<asp:Label ID="idlabel" runat="server" Text="Nothing"></asp:Label>

On Page_Load I can change that label to read "Loaded".

protected void Page_Load(object sender, EventArgs e)
        {   idlabel.Text = "Loaded";     }

The problem is when I try and change the label again after using a button located within my listview.

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" OnItemDataBound="ListView1_ItemDataBound"
            DataSourceID="DataSource" OnItemCommand="ListView1_SelectedIndexChanged"><ItemTemplate><tr><td><asp:Button ID="Button1" runat="server" Text="Change Text" /></td></tr></ItemTemplate>
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            idlabel.Text = "Changed";
            Response.Redirect("MyPage.aspx");
        }

Button uses a command which when using the debug runs with no problems, however the label does not change. The Listview and gridviews contained within (data not posted here) work with no problems.

Hopefully someone can help and let me know where I am going wrong. My overall aim is to put the label into a session variable so I can execute a query with it as a variable.

Thanks in advanced

How to start reading Table or Query from a specific record onwards?

$
0
0

I have a requirement to read an SQL Table or Query STARTING from a specified record (MS Access 2010).

This record could be identified by one unique field within it, not by record number.

Let say we have several records like this:

3054    Part xyz     01

3168    Part abc    02

2089    Part dfg    02

2765    Part ert     03

2945    Part yui     04

3512    Part asd    04

The only unique identifier is the part number which would be passed to my procedure.  So I would like to select all the parts starting from 2089 on, for example.   I cannot SELECT PartNumber>=2089 because I would get 3054 and 3168, which is not the requirement.

Help most appreciated.

why is not declared. It may be inaccessible due to its protection level?

$
0
0

i don't know why i received this error "DTLLigue' is not declared. It may be inaccessible due to its protection level"

<asp:Repeater id="DTLDispo" runat="server" OnItemDataBound="GetDispo_ItemDataBound" >
<ItemTemplate >
<div class="col-lg-3 col-md-3 col-sm-3" style="padding-left:1; padding-right:1;margin-left:0;margin-right:0">
<div class="panel panel-primary">
<div class="row panel-heading" style="padding-left:0; padding-right:0;margin-left:0;margin-right:0;text-align:center;font-size:small">
<%# DateTime.Parse(Eval("Date").ToString()).ToString("dddd dd MMMM yyyy", New System.Globalization.CultureInfo("fr-FR")) %>
</div>
<br />
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="row panel-heading bold" style="padding-left:0; padding-right:0;margin-left:0;margin-right:0;font-size:x-small">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"> Ligue </div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">AM</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">PM</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">SOIR</div>
</div>


<!-- Table -->
<asp:Repeater id="DTLLigue" runat="server">
<ItemTemplate >
<div class="panel-body" style="padding-left:0; padding-right:0;margin-left:0;margin-right:0;font-size:x-small">
<ul class="list-group">
<li class="list-group-item col-lg-6 col-md-6 col-sm-6 col-xs-6">
ABMSE
</li>
<li class="list-group-item col-lg-2 col-md-2 col-sm-2 col-xs-2">
<asp:Literal runat="server" ID="Ltl_DispoAM"></asp:Literal>
</li>
<li class="list-group-item col-lg-2 col-md-2 col-sm-2 col-xs-2">
<asp:Literal runat="server" ID="Ltl_DispoPM"></asp:Literal>
</li>
<li class="list-group-item col-lg-2 col-md-2 col-sm-2 col-xs-2">
<asp:Literal runat="server" ID="Ltl_DispoSOIR"></asp:Literal>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>


</div>
</ItemTemplate>

</asp:Repeater>


code behind:

Dim cnn As New SqlConnection
Dim cm As New SqlCommand
Dim dt As New DataTable
i = 0

dt.Columns.Add("Date", GetType(DateTime))

Do Until i = 30
dt.Rows.Add(DateTime.Now.AddDays(i))
i += 1
Loop

DTLDispo.DataSource = dt
DTLDispo.DataBind()


Try
dt.Clear()
cnn.ConnectionString = ConfigurationManager.ConnectionStrings("ABQLConnectionString").ConnectionString
cnn.Open()
cm.CommandText = "select * from parametres where UserID = '" & UserID & "'"
cm.Connection = cnn
dt.Load(cm.ExecuteReader())
Catch ex As Exception
MsgBox(ex.Message)
Finally
DTLLigue.DataSource = dt
DTLLigue.DataBind()
cnn.Close()
End Try


thank you for your help !

About paging an objectdatasource

$
0
0

Hi all:

I have an objectdatasource

<asp:ObjectDataSource ID="objdspuntosganados" TypeName="comercial.puntos_ganados_datospersonales" SelectCountMethod="seleccionar_cuenta" EnablePaging="true" SelectMethod="seleccionar_todo" StartRowIndexParameterName="comienzo" MaximumRowsParameterName="maximonumeroregistros" SortParameterName="orden" runat="server" ><SelectParameters><asp:Parameter Name="condicion" DefaultValue=" "  /><asp:CookieParameter name="c10" CookieName="cuenta"/><asp:QueryStringParameter Name="idioma" QueryStringField="idioma" /></SelectParameters></asp:ObjectDataSource>

This is the BAL

    Public Class puntos_ganados_datospersonales

        Public Function seleccionar_todo(ByVal idioma As Integer, ByVal c10 As Integer, ByVal orden As String, ByVal comienzo As Integer, ByVal maximonumeroregistros As Integer, ByVal condicion As String) As DataSet
            Dim cnconexion As New SqlConnection(ConfigurationManager.ConnectionStrings("Cresolia").ConnectionString)
            Dim sqlc As New SqlCommand("seleccionar_puntos_ganados_datospersonales", cnconexion)
            Dim da As SqlDataAdapter = New SqlDataAdapter(sqlc), ds As DataSet = New DataSet()
            sqlc.CommandType = CommandType.StoredProcedure
            sqlc.Parameters.AddWithValue("@idioma", idioma)
            sqlc.Parameters.AddWithValue("@c10", c10)
            sqlc.Parameters.AddWithValue("@orden", orden)
            sqlc.Parameters.AddWithValue("@comienzo", comienzo)
            sqlc.Parameters.AddWithValue("@maximonumeroregistros", maximonumeroregistros)
            sqlc.Parameters.AddWithValue("@condicion", condicion)
            cnconexion.Open()
            da.Fill(ds)
            cnconexion.Close()
            Return ds
        End Function

        Public Function seleccionar_cuenta(ByVal idioma As Integer, ByVal c10 As Integer, ByVal condicion As String) As Integer
            Dim cnconexion As New SqlConnection(ConfigurationManager.ConnectionStrings("Cresolia").ConnectionString)
            Dim sqlc As New SqlCommand("seleccionar_numeroregistros_puntos_ganados_datospersonales", cnconexion)
            Dim intnumeroregistros As Integer
            sqlc.CommandType = CommandType.StoredProcedure
            sqlc.Parameters.AddWithValue("@idioma", idioma)
            sqlc.Parameters.AddWithValue("@c10", c10)
            sqlc.Parameters.AddWithValue("@condicion", condicion)
            cnconexion.Open()
            intnumeroregistros = CInt(sqlc.ExecuteScalar())
            cnconexion.Close()
            Return intnumeroregistros
        End Function

    End Class

In the sp I have

	set @comienzo+=1
	set @fin=@comienzo+@maximonumeroregistros-1
...

	select pg0,p0,case @idioma when 1 then ''destino: valoración de ''+(select obra_espanol from dbo.obras where o0=16) when 2 then ''destiny: ''+(select obra_ingles from dbo.obras where o0=16)+'' valuation'' when 3 then ''destin: évaluation des ''+(select obra_frances from dbo.obras where o0=16) when 4 then ''destino: valoração de ''+(select obra_portugues from dbo.obras where o0=16) end,libro,fecha,null,puntos
	from dbo.[puntos ganados] inner join dbo.[valoraciones poemas] on vp0=pg3 inner join dbo.poemas on p0=vp1 where pg1=2 and pg2=51 and p2=@c10
	) tabla0'+ @condicion+') tabla1 where numero between @comienzo and @fin'

The gridview has 16 records and gridview.pagesize=25

However only 10 records are shown. And it doesn't paginate.

What is wrong? Do I forget something?

TIA

How to apply an arbitrary filter expression to ListView?

$
0
0

Hello,

I have a ListView that shows documents. The documents may belong to an organization, a room or whatever. To show the right documents, I pass an arbitrary filter expression to the ListView.

The filter expression is set in the Page Load event. It is then applied as the WHERE-condition in the underlying SQL select command. To apply the filter, the DataBind methods are called for both, the DataSource and the ListView. So far so good...

However, this mechanism causes problems when the user uploads a new document. Then, the ListView's InsertTemplate is shown. The user enters a name in a TextBox (txt_Name) and selects the file to upload. Then, he clicks on a button "Insert", which has an event handler "btn_Insert_Click".

The problem is: When the event handler btn_Insert_Click is executed, the value of the TextBox txt_Name is gone. Why? It's because the ListView's DataBind method is called on every page load, when the filter is set. I have tried to only set the filter when IsPostBack is false, but then the ListView looses its contents.

I have prepared a minimal example below.

What would be a suitable method to do what I want? How would you do this?

Thanks
Magnus

TestUpload.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestUpload.aspx.cs" Inherits="Governix.apl.tst.TestUpload" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head><body><form id="form1" runat="server"><div><asp:SqlDataSource ID="src_Document" runat="server" ConnectionString='<%$ ConnectionStrings:myConStr %>'
                SelectCommand="SELECT * FROM [rsc_v_dokument] WHERE (1=0);"></asp:SqlDataSource><asp:ListView ID="lvw_Document" runat="server" DataSourceID="src_Document" DataKeyNames="idx" InsertItemPosition="LastItem" OnDataBound="lvw_Document_DataBound"><LayoutTemplate><table id="itemPlaceholderContainer"><thead><tr><th align="left">Name</th><th align="left">Action</th></tr></thead><tbody><tr runat="server" id="itemPlaceholder"></tr></tbody></table></LayoutTemplate><ItemTemplate><tr><td align="left"><asp:Label Text='<%# Eval("name") %>' runat="server" ID="lbl1" /></td><td align="left"><asp:LinkButton ID="btn_Edit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton></td></tr></ItemTemplate><InsertItemTemplate><tr style=""><td align="left"><asp:TextBox runat="server" ID="txt_Name" Width="400px" /><br /><asp:FileUpload ID="upl_Document" runat="server" Width="400px" /></td><td><asp:LinkButton ID="btn_Insert" runat="server" CausesValidation="False" Text="Insert" OnClick="btn_Insert_Click"></asp:LinkButton><asp:LinkButton ID="btn_Cancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton></td></tr></InsertItemTemplate></asp:ListView><br /><asp:LinkButton runat="server" ID="btn_New" Text="New" OnClick="btn_New_Click" /><br /><asp:Literal ID="ltr_Status" runat="server"></asp:Literal></div></form></body></html>

TestUpload.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Governix.apl.tst
{
    public partial class TestUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // set filter for document list

            setListFilter("ref_organisation=10 OR ref_raum=26");
        }

        private void setListFilter(String cnd)
        {
            // apply filter to query

            src_Document.SelectCommand = "SELECT idx,name,ctp,icon FROM rsc_v_dokument WHERE (" + cnd + ")";
            src_Document.DataBind();
            lvw_Document.DataBind();
        }

        protected void lvw_Document_DataBound(object sender, EventArgs e)
        {
            // hide InsertItem if not uploading

            FileUpload upl = (FileUpload)lvw_Document.InsertItem.FindControl("upl_Document");

            if (upl.PostedFile == null)
                lvw_Document.InsertItem.Visible = false;
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
            // toggle InsertItem visibility

            lvw_Document.InsertItem.Visible = !lvw_Document.InsertItem.Visible;
        }

        protected void btn_Insert_Click(object sender, EventArgs e)
        {
            // handle file upload

            FileUpload upl = (FileUpload)lvw_Document.InsertItem.FindControl("upl_Document");
            TextBox txt_Name = (TextBox)lvw_Document.InsertItem.FindControl("txt_Name");

            if (upl == null || txt_Name == null)
                return;

            if (!upl.HasFile)
                return;

            if (txt_Name.Text == "")
            {
                ltr_Status.Text = "The name is missing!";
                return;
            }

            // add new document to datbase and requery
            lvw_Document.DataBind();
        }

    }
}

Viewing all 956 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>