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

Passing comma delimited parameter to SP

$
0
0

Is this possible? I find it hard to believe that this could be sooo difficult. I have a simple select stored procedure that has one parameter. My application is passing a comma delimited string of values to be used in the IN clause.

Ex: Where x In(@parametername)

the x column is an integer. How can one work around this???

Thanks![st]


Pass a Datatable of distinct values to a parameter query

$
0
0

I have a selectparameter like:

 ProductSqlDataSource.SelectParameters("CategoryID").DefaultValue = categoryID


Originally it took one parameter value . Now I have multiple values to assign from a DataTable

  CategoryID_Table = results.DefaultView.ToTable(True, "CategoryID")

How do I now extract values from the Datatable and Query the Select statement ?

SQL Query Where clause:

   WHERE        (Product_items.Category = @CategoryID)

Connection.close slow using OleDb

$
0
0

We're developing an n-tier application, using an Access database. We're basically finished with the application, but we're optimising some of the slower pages. Using a profiler and a timer measuring the time spent in rendering, sql and framwork parts of the application we tracked down the lackluster performance to the places where we we called connection.close()(in the try-catch-finally).

If we drop the close statement, performance is many times faster:

Using try-catch-finally and connection.close()
SQL statements: 245
SQL executiontime: 614ms
Framework execution time:11461ms
Page rendering :94ms
Total execution time:11555ms

Without connection.close()
SQL statements: 245
SQL executiontime: 559ms
Framework execution time:1447ms
Page rendering :117ms
Total execution time:1564ms

Any suggestions on why this is happening?

Insert Data to database Controls

$
0
0

Is there an easy way to insert data into the database.
I only know one method to insert data into formviiew ,listview .. etc.
for Example:

         

            Dim txt As Text = FormView1.FindControl("TextBox1")
            SQLDataSource1.InsertCommand = "INSERT INTO Table01(Counter) VALUES ('" & CInt(txt.Text) +1 & "')"
            SQLDataSource1.Insert()
' 😵

Thank you in advance




How to filter with Operator in LINQ Union

$
0
0
<div>

Hello,

I have a problem with filter my list with operator AND and OR.

//In searchField1 DropDownList
Index1 = Title
Index2 = Author1
Index3 = Publisher

//In searchField2 DropDownList
Index1 = Title
Index2 = Author1
Index3 = Publisher

 I can get searchField1 Dropdownlist filter with the following:


 lstFirst = searchField1_Index == 1 ? (lstFirst.Where(fst => fst.Title.Contains(searchKey1))).ToList<oData.vwBook>() :
                        searchField1_Index == 2 ? (lstFirst.Where(fst => fst.Author1.Contains(searchKey1))).ToList<oData.vwBook>() :
                        searchField1_Index == 3 ? (lstFirst.Where(fst => fst.Publisher.Contains(searchKey1))).ToList<oData.vwBook>() :
                        lstFirst.ToList<oData.vwBook>();

and searchField2 Dropdownlist filter with the following:

 lstSecond = searchField2_Index == 1 ? (lstSecond.Where(fst => fst.Title.Contains(searchKey1))).ToList<oData.vwBook>() :
                        searchField2_Index == 2 ? (lstSecond.Where(fst => fst.Author1.Contains(searchKey1))).ToList<oData.vwBook>() :
                        searchField2_Index == 3 ? (lstSecond.Where(fst => fst.Publisher.Contains(searchKey1))).ToList<oData.vwBook>() :
                        lstSecond.ToList<oData.vwBook>();

and I have Operator Dropdownlist with AND and OR. The problem is after selecting the operator Dropdownlist. If User select AND I have to combine 2 List with Union and then I have to filter like...

lstCombine = lstFirst.Union(lstSecond.ToList<oData.vwBook>()).ToList<oData.vwBook>();

//AND operator

lstCombine =(if searchField1 is Title or Author or Publisher which is equal to txtSearch1.Text) AND (if searchField2 is Title or Author or Publisher which is equal to txtSearch2.Text)

//OR operator

lstCombine =(if searchField1 is Title or Author or Publisher which is equal to txtSearch1.Text) OR (if searchField2 is Title or Author or Publisher which is equal to txtSearch2.Text)

Please help !

Best Regards,

Nyi Nyi Aung

</div>

How to write AS statement for the database queries.

$
0
0

 _qryDevice.Append("SELECT DL_TIMESTAMP,");
            _qryDevice.Append("DL_DATA ");
            _qryDevice.Append("FROM TRSDB001.DMSTRS_LOG ");
            _qryDevice.Append("WHERE DL_OUTAGE_TYPE = 'O'");

I am trying to rename the DL_TIMESTAMP Column to TIMESTAMP. I get an error when I add AS statement:  _qryDevice.Append("SELECT DL_TIMESTAMP AS 'TIMESTAMP',");

Could someone please guide me in the right direction?

SQL SERVER EXPRESS EDITION IS FREE TO USE AT CLIENT SIDE?

$
0
0

SQL SERVER EXPRESS EDITION IS FREE TO USE AT CLIENT SIDE?

Passing an array to query in a table adapter

$
0
0

I'm looking for a way to pass an array of values as a parameter to a query in a table adapter.  For example I want to run a query something like:

SELECT * FROM menu WHERE menu_role IN (@roles)

And I could pass something like 'RegisteredUser, SuperUser, OtherUser' to the @roles parameter.

For some reason I can't figure out a way to do this.  Any help would be greatly appericated.

Thanks,

Ryan.



 


Reload ListView inside User Control inside MultiView

$
0
0

Hi,

I want to reload a ListView after a database operation inside a LinkButton click event handler.

When I simply call DataBind(), the ListView simply disappears.

The ListView is bound to a SqlDataSource and lives inside a User Control.

The User Control is one view inside a MultiView.

The MultiView is part of a Web Form with a Master Page...

What can I do?

Thanks
Magnus

SqlDataSource InsertCommand with C#?

$
0
0

Hi,

I need an InsertCommand for a SqlDataSource with a distinction of cases:

if (field1 = "A")
 INSERT INTO table1 (...) VALUES (...);
else
 INSERT INTO table2 (...) VALUES (...);

I cannot do this by setting the InsertCommand property to an INSERT statement.

What I found is that I could use a Stored Procedure.

What else can I do?

Could I attache some C# code to the SqlDataSource that does the insert?

Thanks
Magnus

ListView.EditItemTemplate: On which event can you rebind a DropDownList?

$
0
0

Hi,

I have a ListView with an EditItemTemplate:

<EditItemTemplate><asp:DropDownList ID="lst_Type" runat="server" OnSelectedIndexChanged="lst_Typ_SelectedIndexChanged"
     AutoPostBack="True" SelectedValue='<%# Bind("typ")%>'><asp:ListItem Value="" Text="" /><asp:ListItem Value="A" Text="Type 1" /><asp:ListItem Value="B" Text="Type 2" /><asp:ListItem Value="C" Text="Type 3" /></asp:DropDownList><asp:DropDownList ID="lst_Number" runat="server" OnSelectedIndexChanged="lst_Num_SelectedIndexChanged"
     SelectedValue='<%# Bind("number")%>'></asp:DropDownList></EditItemTemplate>

The specific problem is that the contents of the second DropDownList (lst_Number) depends on the first one (lst_Type).

What I need is an event handler where I can fill the list depending on the current record.

But when I execute the edit command, I get an error, because the data value that should be bound to the list does not exist in the list.

I tried do do this in ListView.OnEditing, but without success...

Please help!

Thanks

Magnus

Select with sqlDataSource, number of rows?

$
0
0

Hi

I need to get the number of rows form sqldatasource. Here is my code:

protected void Button2_Click(object sender, EventArgs e)
    {
        SqlDataSource2.SelectCommand = "select * from clientes where email=?";
        SqlDataSource2.SelectParameters.Add("@bi",email.Text);          
    }

    protected void SqlDataSource2_Selected(object sender, SqlDataSourceStatusEventArgs e)
    {
        int total = e.AffectedRows;
        Response.Write("total de linhas" + total);
        if (total == 0)
        {
            OdbcConnection connection = new OdbcConnection("Dsn=produtos;server=localhost;uid=***;pwd=***;database=***;port=3306");
            OdbcCommand command = new OdbcCommand("INSERT INTO clientes (nome,morada,morada1,postal,localidade,email,telefone) VALUES (?,?,?,?,?,?,?)", connection);
            command.Parameters.AddWithValue("@nome", nome.Text);
            command.Parameters.AddWithValue("@morada", morada.Text);
            command.Parameters.AddWithValue("@morada1", morada1.Text);
            command.Parameters.AddWithValue("@postal", postal.Text);
            command.Parameters.AddWithValue("@localidade", localidade.Text);
            command.Parameters.AddWithValue("@email", email.Text);
            command.Parameters.AddWithValue("@telefone", telemovel.Text);
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
}

Why it doesn't work? The response.write is never executed.

Thank you

ListView and Edit/Update command

$
0
0

Hi,

I have a ListView and I want to implement the insert and update functionality.
Insert works great! But the update procedure doesn't work because in the update procedure I cannot access my controls:

        protected void btn_Update_Click(object sender, EventArgs evt)
        {
            String typ = ((DropDownList)lvw_Zuordnung.EditItem.FindControl("lst_Typ")).SelectedValue;

            ---> NullReferenceException
        }

The same works great in the insert scenario (with ListView.InsertItem),

What can I do?

Thank you very much
Magnus

ListView - Delete Row using SqlDataSource.Delete

$
0
0

Hello,

I have a ListView based on a SqlDataSource:

<ListView>
...<ItemTemplate><td align="left" style="" runat="server"><asp:CheckBox runat="server" ID="chk" /></td><td align="left" style="" runat="server"><asp:Label ID="lbl_Name" runat="server" Text='<%# Eval("name") %>' /></td><td align="left" style="" runat="server"><asp:Label ID="Label1" runat="server" Text='<%# Eval("nummer") %>' /></td><td align="left" style="" runat="server"><asp:Label ID="Label2" runat="server" Text='<%# Eval("modus_name") %>' /></td><td align="left" style="" runat="server"><asp:Label ID="Label3" runat="server" Text='<%# Eval("ausgabe") %>' /></td><td><asp:LinkButton ID="btn_Delete" runat="server" CausesValidation="False" CommandName="Delete"
                         Text="Delete Item" OnClick="btn_Delete_Click"></asp:LinkButton></td></ItemTemplate></ListView>

The SqlDataSource has a DeleteCommand with a parameter:

<asp:SqlDataSource ID="src_Assignment" runat="server" ConnectionString="<%$ ConnectionStrings:StMGP %>"
    SelectCommand="SELECT [idx], [personal], [typ],[name], [nummer],modus,modus_name,ausgabe FROM [assignment] WHERE ([personal] = @idx)"
...
    DeleteCommandType="Text" DeleteCommand="DELETE FROM assignment WHERE (idx=@idx);"><DeleteParameters><asp:Parameter Name="idx" Type="Int32"/></DeleteParameters></asp:SqlDataSource>

When the user clicks on "Delete Item" in one of the rows, the event handler is called:

       protected void btn_Delete_Click(object sender, EventArgs evt)
        {
           // Here I need to set the "idx" parameter of the DeleteCommand:
           // src_Assignment.DeleteParameters.Add("idx",???)
           // How can I get the idx of the row where the delete button was clicked?
        }

How can I do the following:

  • How can I retrieve the value of the "idx" key for the row where the "Delete Item" button was clicked?
  • How can I set the delete parameter to this value?
  • How do I have to call "src_Assignment.Delete()"? Which parameter do I have to pass to this method?
  • Can I view/trace the resulting SQL command before it gets executed?

Thanks

Magnus

Exporting from Sql Server to Excel

$
0
0

The following code is a short version of a process to export data from Sql Server to Excel.  I am moving 300k of data to excel and am having to divide it up into 65500+ blocks.  This is not a problem in classic asp but .net does not seem to like this method.  When ExecuteNonQuery() executes the insert statement each time through the loop it really slows down this process.  Otherwise in runs in seconds commenting out ExecuteNonQuery().  Also it looks like the excel file does not grow until the very end.  I would think it would be inserting every time it did ExecuteNonQuery().  Do I have something wrong here or should I do a completely different method for this?

<div>using (SqlConnection conn = new SqlConnection(sqlConnString)</div> <div>{</div> <div>    conn.open();</div> <div>    da.fill(dt);</div> <div>    conn.Close();</div> <div> </div> <div>    using (OleDbConnection connExcel = new OleDbConnection(connString))</div><div>    {</div> <div>    OleDbCommand cmdExcel = new OleDbCommand(strExcelSql, connExcel;</div> <div>    connExcel.Open;</div> <div>    foreach (DataRow dr in dt.Rows)</div> <div>    {</div> <div>        foreach (DataColumn dc in dt.Columns)</div> <div>       {</div> <div>            if (firstTime)</div> <div>            cmdExcel.Parameters.AddWithValue(name, value);</div> <div>            else</div> <div>            cmdExcel.Parameters[dc.Ordinal].Value = dr.ItemArray[dc.Ordinal].ToString();</div> <div>       }</div> <div>        cmdExcel.ExecuteNonQuery();
    }</div> <div style="FONT-FAMILY: times new roman, new york, times, serif; FONT-SIZE: 12pt" mce_style="FONT-FAMILY: times new roman, new york, times, serif; FONT-SIZE: 12pt">    connExcel.Close;</div> <div style="FONT-FAMILY: times new roman, new york, times, serif; FONT-SIZE: 12pt" mce_style="FONT-FAMILY: times new roman, new york, times, serif; FONT-SIZE: 12pt">    }
}</div>

strExcelSql would be the insert statement Insert Into [Sheet1$A1:Q1] (F1, F2, F3...) Values (?,?,?...)

Also it would be nice if I could push the entire ItemArray instead of doing the parameters column by column


Select and count rows sqldatasource problem

$
0
0

Hi

I need to verify if the sku the user choose is on the table perfumes. I can't accept repetead sku. here is my code:

 SqlDataSource1.SelectCommand = "select * from perfumes where sku=?";
        SqlDataSource1.SelectParameters.Add("@sku", TextBox1.Text);
        DataView dvsqllist = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        DataTable tablelist = dvsqllist.Table;
        int n = tablelist.Rows.Count;

        if (n > 0) {
            Label1.Text = "O SKU já existe";
        }else { 

If n>0 the sku exists and one label indicates the user has to change the sku, but after he changes the sku the n is equal a 1 again . I debbuged the source code and the sku is actualized (with textbox1.text) but the n is 1 again

Can sameone tell me what is happen?

How to bind MYSQL table with SQLDataSource ? VS2013 Tools keeps “SQLServer syntax” with “[ ]”

$
0
0

I search to bind MySQL table in ASP.net GridView with SQLDataSource but I have a problem.

In fact Visual Studio 2013 seems to use "SQLServer syntax" with "[ ]" on tables and fiels in SQL select, update, request...

==> Do you have an idea of where the bug can come from ? It can be MySQL Connector/NET ?

My environnement :

  • Visual Studio 2013 + .NET Framework 4.5.5
  • MySQL 5.6.17 from WAMP 64 bit
  • MysQL Connector/NET 6.8 32 bit
  • MySQL for Visual Studio 1.2.3

dqsdqsdqsd

Thanks for help :)

Sql permissions for the developers

$
0
0

Hi Everyone , I need to give rights pemissions on Databases for developers in such a way that they can do any thing except DB backup and restore. I use SQL Server 2000, In SQL 2005 it is simple I just give db_owner permission and remove dbbackup rights permission for db_owner. but in SQL 2000 I did not find any thing to remove DB backup permission from ob_owner.

Can Anyone help me in setting the correct permissions for developers

resetting database

$
0
0

hi!

i'm new to sql server and enterprise manager and i accidentally deleted all data in a table. how do i recover them? the table (CaptureManager) is still there but empty. i have the following information:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CaptureManager]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[CaptureManager]
GO

CREATE TABLE [dbo].[CaptureManager] (
 [ID] [tinyint] IDENTITY (1, 1) NOT NULL ,
 [Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
 [Email] [varchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
 [Ext] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
 [Status] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

Sql question( select the first, second row in the table)

$
0
0
In MS Sql server, no "first" function,

how to select only the first row?

By the way, how to select only the seoncd row?

Thx
Viewing all 956 articles
Browse latest View live