Accessing Data From A Programmatically Created SqlDataSource

Nov 3, 2007

Hi
I think I've programmatically created a SqlDataSource - which is what I want to do; but I can't seem to access details from the source - row 1, column 1, for example????


If Not Page.IsPostBack Then

'Start by determining the connection string valueDim connString As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

'Create a SqlConnection instanceUsing connString

'Specify the SQL query

Const sql As String = "SELECT eventID FROM viewEvents WHERE eventID=17"

'Create a SqlCommand instanceDim myCommand As New Data.SqlClient.SqlCommand(sql, connString)

'Get back a DataSetDim myDataSet As New Data.DataSet

'Create a SqlDataAdapter instanceDim myAdapter As New Data.SqlClient.SqlDataAdapter(myCommand)

myAdapter.Fill(myDataSet)Label1.Text = myAdapter.Tables.Rows(0).Item("eventID").ToString() -??????????????

'Close the connection

connString.Close()

End Using

End If
Thanks for any help
Richard

 

View 1 Replies


ADVERTISEMENT

Programmatically Accessing An SQLDataSource With A SELECT COUNT(*) Query.

Jun 20, 2007

I've found example code of accessing an SQLDataSource and even have it working in my own code - an example would be  Dim datastuff As DataView = CType(srcSoftwareSelected.Select(DataSourceSelectArguments.Empty), DataView)  Dim row As DataRow = datastuff.Table.Rows(0)   Dim installtype As Integer = row("InstallMethod")  Dim install As String = row("Install").ToString  Dim notes As String = row("Notes").ToString The above only works on a single row, of course. If I needed more, I know I can loop it.The query in srcSoftwareSelected is something like "SELECT InstallMethod, Install, Notes FROM Software"My problem lies in trying to access the data in a simliar way when I'm using a SELECT COUNT query. Dim datastuff As DataView = CType(srcSoftwareUsage.Select(DataSourceSelectArguments.Empty), DataView) Dim row As DataRow = datastuff.Table.Rows(0) Dim count As Integer = row("rowcnt") The query here is "SELECT COUNT(*) as rowcnt FROM Software"The variable count is 1 every time I query this, no matter what the actual count is. I know I've got to be accessing the incorrect data member in the 2nd query because a gridview tied to srcSoftwareUsage (the SQLDataSource) always displays the correct value. Where am I going wrong here?  

View 6 Replies View Related

Help: Programmatically Update Data From An SQLDataSource (C#)

Jul 3, 2007

ello all
 Would someone be so kind as to save me from getting balder through pulling my hair out.
My aim is to extract data from a database using SQLDataSource, then edit the data and update the database using the SQLDataSource.
I have achieve the problem of retrieving the data from the sqlDataSource:DataView openRemindingSeats = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);        //Int32 openRemindingSeats = SqlDataSource2.Select(DataSourceSelectArguments.Empty), DataView;
        foreach (DataRowView rowProduct in openReminding)        {            //Output the name and price            lbl_NumOfSeatsLeft.Text = rowProduct["Remaining"].ToString();
        }
Within the sqlDataSource the sql code is as follows:SELECT [refNumber], [refRemaining] FROM [refFlights] WHERE ([refNumber] = @Number)
So at the moment my problems is being able to edit and update data to the same SELECTed data.Thank you for any help that you might have...
SynDrome

View 8 Replies View Related

How Do I Programmatically Inert Data Using A SqlDataSource Control?

May 19, 2007

I just want to insert a record into a table using a SqlDataSource control.  But I'm having a hard time finding examples that don't use data bound controlsI have this so far (I deleted the parts not related to the insert):<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:UserPolls %>"    InsertCommand="INSERT INTO [PollAnswers] ([PollId], [AnswerText], [AnswerCount]) VALUES (@PollId, @AnswerText, @AnswerCount)"    <InsertParameters>        <asp:Parameter Name="PollId" Type="Int32" />        <asp:Parameter Name="AnswerText" Type="String" />        <asp:Parameter Name="AnswerCount" Type="Int32" />    </InsertParameters> </asp:SqlDataSource> This is the data source for a gridview control I have on the page.  I could set up an SqlDataSource for this alone if I need to, but i don't know if it would help.  From what I could find, in the code behind I should haveSqlDataSource2.Insert()and SqlDataSource2  will grab the parameters and insert the record.  The problem is I need to set the Pollid (from a session variable) and AnswerText (from a text box) at run time.  Can I do this?Diane 

View 3 Replies View Related

SqlDataSource - Need To Refresh Grid When Data Updated Programmatically

Nov 27, 2007

I am sending a GUID to a form via the query string.  If it exists I use helper functions to load most of the form text boxes.  However, if it does not then a blank form is presented and the GUID is stored in a hidden field. 
Regardless, I use this hidden field to populate a grid that is attached to a sqldatasource.
If I then add new datarows to the backend database programmatically, I cannot 'requery' the datasource to include those row upon a postback.  I cannot seem to find a simple way to force the sqldatasource to rerun the query.
Can anyone help.

View 2 Replies View Related

Accessing Data From The SQLDataSource.

Apr 5, 2008

I am using a drap and drop SQLDataSource control.  Everything works like I am wanting it to, but I want to check a value from one of the fields that I have retrieved.  I am lost as how to retreive just the field.  If I have to create another dataset to do the work what is the point of using the drag and drop control?  I would really like to just access the dataset fields as needed.

View 2 Replies View Related

Accessing Data Directly From A SqlDataSource?

Mar 7, 2007

First let me give you a little back ground on me.  I'm very new to the ASP, ASP.NET, Visual Studio, Sql Server, Frameworks....thing.  I am coming over from a PHP/MySql background of over 5 years.  The change over to VBScript and VB has been to tough and I have a basic liking for the Visual Studio 2005 and the ease of putting things together.  However, I have come across something that to me seems like it should be relatively simple, but haven't been able to find the documentation or samples to describe what I'm looking to do.
Rough Need:
1.  Start with a form will a couple labels and a singe textbox to get the lookup date from an user.
2.  Query one table/view based on the users choice of date and select only one field of returned data.(Doing this by itself is not a problem and I can display my results in a Gridview, but this is where it starts getting tricky and the gridviews won't work for me.)
3.  If there is something returned, I need to start a HTML table layout or possibly some form of a Gridview(I don't see how I would use the Gridview) and start a loop, adding the first returned row from this query into the first cell.
4.  Now, based on that same User Date and the returned row value from the previous query, I need to query another Table/view and return another single field, which might return 1 or multiple rows, which I need to start a loop to display unique items in cells under the first on above.
5.  Based on the original User Date and each returned row from the first query, I need to query two other Table/views and get some additional information.  4-5 fields will be returned and be displayed on one row in the number of necessary columns.
6.  This would finish the first row from the first query, so I would need to loop back up to see if there were any further results and continue looping until the get to the last of the results from the first query.
7.  Finally, I would just need to close up the Table/gridview.
The basic results I'm looking for would be similar to the following:
Results for 10/11/2005



Field name 1
Field name 2
Field name 3
Field name 4
Field name 5



First Result from query 11 of 4 results from Query 2, but only 1 unique result

Info from Query 3

Info from Query 3
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3
Info from Query 3.
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3

Info from Query 3   
 
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3
Info from Query 3
Info from Query 3
Info from Query 4
Info from Query 4



Second Result from query 1First result from Query 2 after looping though the first query Second result from Query 2 after looping though the first query

Info from Query 3

Info from Query 3
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3
Info from Query 3.
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3

Info from Query 3   
 
Info from Query 3
Info from Query 4
Info from Query 4

Info from Query 3
Info from Query 3
Info from Query 3
Info from Query 4
Info from Query 4
It seems me from what I have read and slowly figuring out, is that I should be able to directly access the DataSet returned by four SqlDataSources, one for each of the above querys and then just write my own VB to handle the necessary looping, table format and such.  I can easily add the for SqlDataSources to the page and add a Gridview for each one and get 4 separate chunks of info, but can't see a way with GridViews to intermingle the info like displayed above.
So, if it can be done with Gridviews, then I would love to see how that is done.  But, if someone could explain to me how I access the DataSets directly that I get from the 4 SqlDataSources, then that would be ok too.  I have figured enough out with VB, that I can write the code to do my looping requirements, if I can just access the information I get back.  Thanks for reading all the way through this long post.
 Jack 

View 1 Replies View Related

SQLDATASOURCE ~ ACCESSING DATA PROGRAMATICALLY

May 9, 2007

Can anyone point me in the direction of code that will allow me to acce3ss the data held in an SQLDataSource.
 
The Control is link Selection Staement has been set at run, what I want to do is loop thru any data that is rertrieved, setting oter controls on the page depending on values
 Thanks
 Steve (I have not got much hair left, please help soon)

View 3 Replies View Related

Accessing Query Execution Plan Results Programmatically

Mar 19, 2007

Does anyone know if it is possible to access the execution plan results programmatically through a stored procedure or .NET assembly? I have the code sample

SET SHOWPLAN_XML ON; query... SET SHOWPLAN_XML OFF;

but it can only be run from the interface. I have tried a couple of solutions including dynamic sql to try to capture the results in a variable or file with no luck.

Does anyone know of a way to programmatically capture this information? We are doing some research with distributed query processing of dynamically generated queries using multiple processing nodes, and it would be helpful to know an estimate of how large the query is before sending it away to be processed.

I have looked at the dm_exec_query_stats view; but it can only be run on a query that has already been executed. I need to know the execution plan before the query is executed. If there is a way to get a query to show up in this view without being executed, then that would work as well.

Thanks -- MT

View 3 Replies View Related

Programmatically Created SSIS Package, CSV File To OLDDB (SQLSever 2005)

Sep 23, 2007

Hi everyone,

I wanted to thank everyone for posting a ton of valuable information in these forums. I also want to thank all the moderators that have been replying with really insightful help!

I am trying to programmatically create an SSIS package to take .CSV data and put it into a SQL Server 2005. I am assuming that this is pretty common scenario.

I have used many of the examples in this forum as well as heavily borrowing from this example http://www.codeproject.com/csharp/Digging_SSIS_object_model.asp written by Moim Hossain.

I can get my package to create and execute properly but no data is being written to the SQL Server table. This has puzzled me for the last 2 days!

I know the issue isnt with the server itself because I tested it by graphically creating a test SSIS package and it transfers the .CSV data to the table perfectly.

Would anyone know why this would happen? The Execution results are returning success but no data is written to the table!

Could anyone please provide insight as to what my issue may be?

Thanks in advance!





Code Snippet

using System;
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime;
using PipeLineWrapper = Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;

namespace SumCodeApp
{
class SumCodeApp
{
// Variables.
private Package package;
private ConnectionManager flatFileConnectionManager;
private ConnectionManager destinationDatabaseConnectionManager;
private Executable dataFlowTask;
private List<String> srcColumns;

int file_count;
SqlConnection connection;

String folder_path;
String username;
String password;
String DB_server;
String catalog;

// Default Constructor.
public SumCodeApp()
{
}

// Constructor taking in user info.
public SumCodeApp(String folder_path, String username, String password,
String DB_server, String catalog)
{
this.folder_path = folder_path;
this.username = username;
this.password = password;
this.DB_server = DB_server;
this.catalog = catalog;
}

private void CreatePackage()
{
package = new Package();
package.CreationDate = DateTime.Now;
package.ProtectionLevel = DTSProtectionLevel.DontSaveSensitive;
package.Name = "SumCode Package";
package.Description = "Upload the SumCode files to the database";
package.DelayValidation = true;
package.PackageType = DTSPackageType.DTSDesigner90;
}

private void CreateFlatFileConnection()
{
String flatFileName = ".1105.csv";
String flatFileMoniker = "FLATFILE";
flatFileConnectionManager = package.Connections.Add(flatFileMoniker);
flatFileConnectionManager.Name = "SSIS Connection Manager for Files";
flatFileConnectionManager.Description = String.Concat("SSIS Connection Manager");
flatFileConnectionManager.ConnectionString = flatFileName;

// Set some common properties of the connection manager object.
//flatFileConnectionManager.Properties["ColumnNamesInFirstRow"].SetValue(flatFileConnectionManager, false);
flatFileConnectionManager.Properties["Format"].SetValue(flatFileConnectionManager, "Delimited");
flatFileConnectionManager.Properties["TextQualifier"].SetValue(flatFileConnectionManager, """);
flatFileConnectionManager.Properties["RowDelimiter"].SetValue(flatFileConnectionManager, "
");
flatFileConnectionManager.Properties["DataRowsToSkip"].SetValue(flatFileConnectionManager, 0);

// Create the source columns into the connection manager.
CreateSourceColumns();
}

private void CreateSourceColumns()
{
// Get the actual connection manager instance
RuntimeWrapper.IDTSConnectionManagerFlatFile90 flatFileConnection = flatFileConnectionManager.InnerObject as RuntimeWrapper.IDTSConnectionManagerFlatFile90;

RuntimeWrapper.IDTSConnectionManagerFlatFileColumn90 column;
RuntimeWrapper.IDTSName90 name;

// Fill the source column collection.
srcColumns = new List<String>();
srcColumns.Add("CreateDate");
srcColumns.Add("CorpID");
srcColumns.Add("SumCodeID");
srcColumns.Add("Priority");
srcColumns.Add("SumCodeAbv");
srcColumns.Add("SumCodeDesc");
srcColumns.Add("SumCodeGroupID");

foreach (String colName in srcColumns)
{
column = flatFileConnection.Columns.Add();
if (srcColumns.IndexOf(colName) == (srcColumns.Count - 1))
//column.ColumnDelimiter = "
";
column.ColumnDelimiter = "{CR}{LF}";
else
//column.ColumnDelimiter = ",";
column.ColumnDelimiter = "Comma {,}";

name = (RuntimeWrapper.IDTSName90)column;
name.Name = colName;

column.TextQualified = true;
column.ColumnType = "Delimited";
column.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
column.ColumnWidth = 0;
column.MaximumWidth = 255;
column.DataPrecision = 0;
column.DataScale = 0;

}

}

private void CreateDestinationDatabaseConnection()
{
destinationDatabaseConnectionManager = package.Connections.Add("OLEDB");
destinationDatabaseConnectionManager.Name = "Destination Connection - SumCodeCorpGroup";
destinationDatabaseConnectionManager.Description = "Connection to the temporary table SumCodCorpGroup";
destinationDatabaseConnectionManager.ConnectionString = "Data Source=DIVWL-356KCB1;Initial Catalog=SumCode;Provider=SQLOLEDB;Persist Security Info=True;User ID=sum;Password=code";
}

public class Column
{
private String name;
private Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType dataType;
private int length;
private int precision;
private int scale;
private int codePage = 0;

public String Name
{
get { return name; }
set { name = value; }
}

public Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType DataType
{
get { return dataType; }
set { dataType = value; }
}

public int Length
{
get { return length; }
set { length = value; }
}

public int Precision
{
get { return precision; }
set { precision = value; }
}

public int Scale
{
get { return scale; }
set { scale = value; }
}

public int CodePage
{
get { return codePage; }
set { codePage = value; }
}
}

private Column GetTargetColumnInfo(string sourceColumnName)
{
Column cl = new Column();
if (sourceColumnName.Contains("CreateDate"))
{
cl.Name = "CreateDate";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (
sourceColumnName.Contains("CorpID"))
{
cl.Name = "CorpID";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (sourceColumnName.Contains("SumCodeID"))
{
cl.Name = "SumCodeID";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (sourceColumnName.Contains("Priority"))
{
cl.Name = "Priority";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (sourceColumnName.Contains("SumCodeAbv"))
{
cl.Name = "SumCodeAbv";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (sourceColumnName.Contains("SumCodeDesc"))
{
cl.Name = "SumCodeDesc";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
else if (sourceColumnName.Contains("SumCodeGroupID"))
{
cl.Name = "SumCodeGroupID";
cl.DataType = Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_STR;
cl.Precision = 0;
cl.Scale = 0;
cl.Length = 255;
cl.CodePage = 1252;
}
return cl;
}

private void CreateDataFlowTask()
{
String dataFlowTaskMoniker = "DTS.Pipeline";
dataFlowTask = package.Executables.Add(dataFlowTaskMoniker);

}

public void ImportFile(String directory_path)
{
// Create the package.
CreatePackage();

// Create Flat File Source Connection.
CreateFlatFileConnection();

// Create Database Destination Connection.
CreateDestinationDatabaseConnection();

// Create DataFlowTask.
CreateDataFlowTask();

// Create the DataFlowTask
PipeLineWrapper.IDTSComponentMetaData90 sourceComponent = ((dataFlowTask as TaskHost).InnerObject as PipeLineWrapper.MainPipe).ComponentMetaDataCollection.New();
sourceComponent.Name = "Source File Component";
sourceComponent.ComponentClassID = "DTSAdapter.FlatFileSource";

PipeLineWrapper.CManagedComponentWrapper managedFlatFileInstance = sourceComponent.Instantiate();
managedFlatFileInstance.ProvideComponentProperties();
sourceComponent.RuntimeConnectionCollection[0].ConnectionManagerID = flatFileConnectionManager.ID;
sourceComponent.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(flatFileConnectionManager);

managedFlatFileInstance.AcquireConnections(null);
managedFlatFileInstance.ReinitializeMetaData();


Dictionary<String, int> outputColumnLineageIDs = new Dictionary<String, int>();
PipeLineWrapper.IDTSExternalMetadataColumn90 exOutColumn = null;

foreach (PipeLineWrapper.IDTSOutputColumn90 outColumn in sourceComponent.OutputCollection[0].OutputColumnCollection)
{
exOutColumn = sourceComponent.OutputCollection[0].ExternalMetadataColumnCollection[outColumn.Name];
managedFlatFileInstance.MapOutputColumn(sourceComponent.OutputCollection[0].ID, outColumn.ID, exOutColumn.ID, true);
outputColumnLineageIDs.Add(outColumn.Name, outColumn.ID);
}
managedFlatFileInstance.ReleaseConnections();


String a = sourceComponent.RuntimeConnectionCollection[0].Name.ToString();
String b = sourceComponent.OutputCollection[0].Name;
String c = sourceComponent.OutputCollection[0].Description;
String d = sourceComponent.OutputCollection[0].OutputColumnCollection.Count.ToString();

// Create DataFlowTask Destination Component.
PipeLineWrapper.IDTSComponentMetaData90 destinationComponent = ((dataFlowTask as TaskHost).InnerObject as PipeLineWrapper.MainPipe).ComponentMetaDataCollection.New();
destinationComponent.Name = "OLEDB SQL Connection";
destinationComponent.ComponentClassID = "DTSAdapter.OLEDBDestination";

PipeLineWrapper.CManagedComponentWrapper managedOleInstance = destinationComponent.Instantiate();
managedOleInstance.ProvideComponentProperties();

// Create a path and attach the output of the source to the input of the destination.
PipeLineWrapper.IDTSPath90 path = ((dataFlowTask as TaskHost).InnerObject as PipeLineWrapper.MainPipe).PathCollection.New();
path.AttachPathAndPropagateNotifications(sourceComponent.OutputCollection[0], destinationComponent.InputCollection[0]);

destinationComponent.RuntimeConnectionCollection[0].ConnectionManagerID = destinationDatabaseConnectionManager.ID;
destinationComponent.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.ToConnectionManager90(destinationDatabaseConnectionManager);

managedOleInstance.SetComponentProperty("AccessMode", 0);
managedOleInstance.SetComponentProperty("OpenRowset", "[SumCode].[dbo].[SumCodeCorpGroup]");
managedOleInstance.SetComponentProperty("AlwaysUseDefaultCodePage", false);
managedOleInstance.SetComponentProperty("DefaultCodePage", 1252);
managedOleInstance.SetComponentProperty("FastLoadKeepIdentity", false); // Fast load
managedOleInstance.SetComponentProperty("FastLoadKeepNulls", false);
managedOleInstance.SetComponentProperty("FastLoadMaxInsertCommitSize", 0);
managedOleInstance.SetComponentProperty("FastLoadOptions","TABLOCK,CHECK_CONSTRAINTS");

managedOleInstance.AcquireConnections(null);
managedOleInstance.ReinitializeMetaData();

PipeLineWrapper.IDTSInput90 input = destinationComponent.InputCollection[0];
PipeLineWrapper.IDTSVirtualInput90 vInput = input.GetVirtualInput();

foreach (PipeLineWrapper.IDTSVirtualInputColumn90 vColumn in vInput.VirtualInputColumnCollection)
{
//if (outputColumnLineageIDs.ContainsKey(vColumn.LineageID.ToString()))
//{
managedOleInstance.SetUsageType(input.ID, vInput, vColumn.LineageID, Microsoft.SqlServer.Dts.Pipeline.Wrapper.DTSUsageType.UT_READONLY);
//}
}

List<String> tmp = new List<String>();
foreach(PipeLineWrapper.IDTSInputColumn90 inc in destinationComponent.InputCollection[0].InputColumnCollection)
{
tmp.Add(inc.Name);
}



PipeLineWrapper.IDTSExternalMetadataColumn90 exColumn;
foreach (PipeLineWrapper.IDTSInputColumn90 inColumn in destinationComponent.InputCollection[0].InputColumnCollection)
{
exColumn = destinationComponent.InputCollection[0].ExternalMetadataColumnCollection[inColumn.Name];
Column mappedColumn = GetTargetColumnInfo(exColumn.Name);
String destName = mappedColumn.Name;

exColumn.Name = destName;

managedOleInstance.MapInputColumn(destinationComponent.InputCollection[0].ID, inColumn.ID, exColumn.ID);
}

managedOleInstance.ReleaseConnections();

DTSExecResult result = package.Execute();
a = "0";
}

}
}

View 3 Replies View Related

Creating SQLDataSource Programmatically?

Apr 17, 2007

Hello. Im trying to create an SQLDataSource control programmatically. I need to do this because I want to do some stuff on my MasterPage's 'Page_Init' event.
 heres my code (Master.master.vb): Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
lblUser.Text = Page.User.Identity.Name

Dim PUser As New ControlParameter
PUser.ControlID = "lblUser"
PUser.Name = "LoginName"
PUser.PropertyName = "Text"
PUser.Type = TypeCode.String
PUser.DefaultValue = Page.User.Identity.Name

Dim SQLDS_Login As New SqlDataSource
SQLDS_Login.ID = "SQLDS_Login"
SQLDS_Login.ConnectionString = "I put conection string here. How do I use the one on my web.config?"
SQLDS_Login.SelectCommand = "SELECT [LoginID], [LoginName], [Role], [Status] FROM [myLogin] WHERE ([LoginName] = @LoginName)"
SQLDS_Login.SelectParameters.Add(PUser)
SQLDS_Login.SelectCommandType = SqlDataSourceCommandType.Text

GridView1.DataSource = SQLDS_Login
GridView1.DataBind()

End Sub
 
When i run, i get this error message:
The SqlDataSource control 'SQLDS_Login' does not have a naming container.  Ensure that the control is added to the page before calling DataBind.
 I never had any problem with Inserts, Updates and Deleting, but I have never made it work for Select when doing it programmatically.
Can you help me with this?

View 1 Replies View Related

Programmatically Add ArrayList Into To Sqldatasource.

Jul 15, 2007

I am trying to add a number of dates into a Sql database.  Basically I want the user to add the start and end date and then all the dates in between are are added to a database in unique records. I can create an ArrayList but I don't know how to bind it to an SqlDataSource   Dim startdate As DateTime = tbstartdate.Text Dim enddate As DateTime = tbenddate.Text Dim datediff As TimeSpan = enddate.Subtract(startdate) Dim noofdays As Integer = datediff.Days Dim ar As New ArrayList Dim i For i = 0 To noofdays ar.Add(startdate.AddDays(i)) Next Sorry if this is a total noob question.... 

View 1 Replies View Related

Programmatically Specify SqlDataSource Parameters

Apr 27, 2006

I have a GridView bound to a SqlDataSource. On page load I would like to programmatically specify a SelectParameter value based on the role of the user. This SelectParameter will be used in my WHERE clause. The closest post I can find is http://forums.asp.net/thread/1233258.aspx but no answer was posted.
What code would I use to modify a SelectParameters value? Is it possible to reference a parameter by name (SqlDataSource1.SelectParameters["usertype"]) or does it have to be by index? (SqlDataSource1.SelectParameters[0])
Alternatively, perhaps I'm going about this in the wrong way, is there a better way to have dynamic GridView content based on the role of the user?
Thank you very much for your help.

View 3 Replies View Related

Accessing SQL Database Created In Visual Studio

Jul 29, 2006

I created an SQL database in Visual Studio 2005 Express Edition and would like to edit it in SQL Server Management Studio Express.  The only databases listed in the Object Explorer of SQL Server MSE are the system databases (ones that are part of the SQL Server MSE). 
If I dig through the directories, I can locate my database under the Visual Studio directory, but I am unable to open it.  I get an error message stating, "There is no editor available for [my database]... Make sure the application for the file type (.mdf) is installed."
I'm sure that this is a ridiculously simple rookie mistake that I'm committing somehow, but I'm stumped.  Any idea what I'm doing wrong?

View 3 Replies View Related

Refresh An SQLDataSource Object Programmatically

Oct 27, 2006

Background - I have a page that uses a numeric value stored in a Session object variable as the parameter for three different SQLDataSource objects, which provide data to two asp:Repeaters and an asp:DataList.  Also, in the Page_Load, I use this value to to seed a stored procedure and an SQLDataReader to populate several unbound Labels.  This works fine.  In addition, I have a collection of 6 TextBoxes, an unbound Listbox, and two Buttons to allow the user to do searching and selection of potential matches.  This basically identifies a new numeric value that I store in the Session variable and PostBack the page (via one of the buttons).  This also works fine.Problem - I have been tasked with taking a different page and adding six textboxes to collect the search values, but to post over to this page, populate the existing search-oriented TextBoxes, adn programmatically triggering the search.  Furthermore, I have to detect the number of matching records and, if only 1, have the Repeaters and DataList display the results based on the newly selected record's key numeric value, as well as populating the unbound Labels.  I have managed to get all of this accomplished except for programmatically triggering the Repeaters and DataList "refresh".  These controls only populate as expected if a button is clicked a subsequent time, which makes sense, since that would trigger a PostBack and the Page_Load uses the new saved numeric key value from the Session.My history in app development is largely from Windows Forms development (VB6), this is my second foray into Web Form dev with ASP.NET 2.0.  I am willing to acceptthat what I am trying to do does not fit into the ASP environment, but I have to think that this is something that has been done before, and (hopefully) there is a way to do what I need.  Any ideas, oh great and wise Forum readers? *smile* 

View 3 Replies View Related

How To Programmatically Construct The UpdateCommand For SqlDataSource

Aug 1, 2007

Hi, All
I'm using Gridview and SqlDataSource to dynamically display the contents in different tables, as followed:
<%   dataSource.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["connectionString"];   dataSource.SelectCommand = "SELECT * FROM " + tableName;   gridView.DataBind();
   dataSource.UpdateCommand = "";%>
<asp:SqlDataSource ID="dataSource" runat="server"></asp:SqlDataSource><asp:GridView ID="gridView" runat="server" DataSourceID="dataSource" AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="True" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" PageSize="20" DataKeyNames="ID" OnRowDataBound="tableGridView_RowDataBound">    <HeaderStyle BackColor="#C0C0FF" />    <AlternatingRowStyle BackColor="#C0FFC0" /></asp:GridView>
The datasource take the "tableName" as argument to determine which table to display. My problem is I can't figure out a way to programmatically construct the UpdataCommand for the SqlDataSource. I try to get the field names from the HeaderRow, but all the cells are empty in this row.
Does anyone know what causes the problem or how to construct the UpdateCommand properly. Thanks!

View 3 Replies View Related

Using SqlDatASource Programmatically - Output Parameters

May 13, 2006

I am using SqlDataSource programmatically in my data access layer - mainly for convenience but it does generally work fine with no obvious performance issues.
The problem I have is with getting back an output parameter. I have an insert-type stored procedure (in Sql Server 2005) operating on a table with an identity column as the primary key:
ALTER PROCEDURE [dbo].[InsertAlbum](@ArtistID int, @Title nvarchar(70), @NewID int OUTPUT)ASDECLARE @err intINSERT INTO dbo.ALBUMS (ARTISTID, TITLE)VALUES (@ArtistID, @Title)SELECT @err = @@error IF @err <> 0 RETURN @errSET @NewID = SCOPE_IDENTITY()
This works fine when run from Sql Server Management Studio and @NewID has the correct value.
My data access code is roughly as follows:
dsrc = New SqlDataSource()dsrc.ConnectionString = ConnectionStringdsrc.InsertCommand = "InsertAlbum"dsrc.InsertCommandType = SqlDataSourceCommandType.StoredProcedureDim parms As ParameterCollection = dsrc.InsertParametersDim newid As IntegerAddParameter(parms, "ArtistID", TypeCode.Int32, ParameterDirection.Input, 0, album.ArtistID)AddParameter(parms, "Title", TypeCode.String, ParameterDirection.Input, 0, album.Title)Dim p As New Parameter("NewID", TypeCode.Int32)p.Direction = ParameterDirection.Outputparms.Add(p)Try   Dim rv As Integer = dsrc.Insert()   newid = parms("NewID")   Return newidCatch ex As Exception   Return -1End Try
The row is inserted into the database, but however I try to define and add the NewID parameter it never has a value.
Has anyone tried to do this and can tell me what I am doing wrong?
Jon
 

View 8 Replies View Related

Programmatically Setting UpdateParameters For A SQLDataSource Control

Sep 8, 2006

I need to provide defaults and sometimes overrides for items in SQLDataSource's UpdateParameters. I am attempting to do this in a FormView's ItemUpdating and ItemInserting events as follows: //========================================================================
// FormView1_ItemUpdating:
//========================================================================
protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e) {
// not sure if this is the bets place to put this or not?
dsDataSource.UpdateParameters["UpdatedTS"].DefaultValue = DateTime.Now.ToString();
dsDataSource.UpdateParameters["UpdatedUserID"].DefaultValue = ((csi.UserInfo)Session["UserInfo"]).QuotaUserID;
}
 In the example above I am attempting to set new values for the parameters which will replace the existing values. I have found that using the DefaultValue property works ONLY if there is no current value for the parameter.  Otherwise the values I specify are ingnored.The parameters of an ObjectDataSource provide a Value property but SQLDataSource parameters do not.How can I provide an override value without needing to place the value in the visible bound form element???If you can answer this you will be the FIRST person ever to answer one of my questions here!!!Thanks,Tony 

View 2 Replies View Related

SQLDataSource Provide Select Parameter Value Programmatically

Sep 9, 2007

Hey All for some reason I can not get this right and/or find what I am looking for.
I have an SQLDataSource with a PartID set as the filtered value in the Datasource Query.
I am trying to use code beside to set the value and I am failing...lol...
Here is my attempt at it,
SqlDataSource1.SelectParameters("PartID") = txtPartID.Text
Any help would be great!

View 2 Replies View Related

Programmatically Getting The Field Values Form An Sqldatasource Control

Oct 10, 2006

Im ripping my hair out here.I need to access the field in a datasource control of use in non presentation layer code based actions.I know the I can use a code base connection and query but I dont see why i need to make two trips the the DB when the info is already available.The datasource is attached to a details view control and the details view control is nested in a loginview controlI've tried defining but all I can get in the header name of the field but not the dataitem, the dataitem causes an error  help please jim

View 4 Replies View Related

Programmatically Loop Through Sqldatasource - Which Event To Place It In...to Get The Right Order....

Mar 7, 2008

Hello,  I want to loop through the first 10 records that are showing in a gridview with several pages that is populated by a sqldatasource.  I can loop through the sqldatasource and get the list of values, but I'm doing something wrong because the 10 records it prints out are not the same 10 records the user sees in the gridview...They can click a search button which changes the sort, and they can click on the column headings to change the sort order.
Where's the best place to put the looping code?  I need the result to be the same as what the users sees. 
  1        Protected Sub GridView1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.Sorted2            Dim i As Integer = -13            Dim sTest As String = ""4            Dim vwExpensiveItems As Data.DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), Data.DataView)5    6            'Loop through each record7            i = -18            For Each rowProduct As Data.DataRowView In vwExpensiveItems9                i = i + 110               'Output the name and price11               If i > 9 Then12                   Exit For13               End If14               sTest = rowProduct("employeeid")15               Response.Write("RowSorting " & i.ToString & " [" & sTest & "]<br>")16           Next17       End Sub18    

View 3 Replies View Related

Closing A Connection Created From A SQLDataSource

Jun 20, 2006

I'm new to ASP.NET and I've searched before posting. I have a simple form containing a FormView control. The FormView uses a SQLDataSource. This works fine and in 30 seconds I have a working form without writing any code.A form built this way causes problems with connection pooling because I am not closing the connection. What is the best method for me to remedy this? Every resource I've found explains that I have to explicitly close the connection. How do I do that in this case? Dispose the SQLDataSource in the FormView DataBound event? Rewrite the form so I can control opening and closing of the connection?Thanks in advance.

View 1 Replies View Related

Accessing Value From SqlDataSource

Jan 24, 2007

I have a SqlDataSource that returns a list of companies and their details by ProductID.  It also returns the name of the product associated with the ProductID as the final column (which means it appears for every record returned).  I already have a way of determining how many rows were returned, and use that information in a label to say "Your search has returned x records". protected void dsGetSuppliersByProduct_Selected(object sender, SqlDataSourceStatusEventArgs e)    {        int RecordCount = e.AffectedRows;        if (RecordCount == 0)        { lblRecordCount.Text = "<p>No Records found"; }        else        {            if (RecordCount == 1)            { lblRecordCount.Text = "<p>Your search returned 1 record"; }            else            { lblRecordCount.Text = "<p>Your search returned " + RecordCount + " records"; }        }        string ProductName;    }How can I access the ProductName value so that I can extend the label text to say "Your search has returned x records for <ProductName>" ?

View 1 Replies View Related

Accessing SqlDataSource's Value In Code Behind

May 30, 2007

Hi guys,

I have following query in stored procedure  Select ContractId, Version, CreateDate, body, IsCurrentFrom CRM_Contracts where ContractId=@ContractId I am trying to access the value of IsCurrent field in Code behind using sqlDataSource to hide a radiobutton list in Formview control's when it is in Edit Mode.  How can i do this.  

View 1 Replies View Related

Created SQL Server Database Using SYBASE DLL &&amp; Data, But Data Problem

Jan 21, 2008



Hello,

I took our SYBASE DDL and created the tables on an SQL Server Express datbase on a PC and then downloaded our data from UNIIX using the WinSCP utility and BULK Inserted the data into the SQL Server database and everything uploaded fine apparently, but when we go to use the data we are getting some data differences.


Do you know of any data conversion issues that may be coming into play here maybe?

Thanks very much!
BobK

View 1 Replies View Related

Programmatically Create Data Sources

Apr 20, 2006

Is there a way to do this? It does not appear as part of the standard SSIS API.

Thanks.

View 4 Replies View Related

Programmatically Determine That A Report Has No Data?

Apr 2, 2008



I'm creating ssrs reports via the web service render method & would like to be able to determine when a report has no data.

Currently what I'm doing is rendering the report twice - once as a pdf (the format that the report needs to be in) and once as a csv. I then check the csv for a specific string placed in the norows property of the report table.

Is there a better way of doing this? It seems to me that this would have been a good candidate to include in the warnings array.

Between this issue & the hacks required to get data into the header I'm thinking that I should maybe reconsider some other reporting options...

Thanks.

View 3 Replies View Related

I Am Accessing Data Using Data Access Pages In IIS 7 To SQL Server 2005 Authentication Is Failing

Feb 5, 2007

is there a step by step paper to get there? here is what i need to consider. I Iwill have many customers that will need their own set of records and access pages "branded for their company" each customer will have many clients. I am hosting this application on a windows 2003 server with SQL 2005 server enterprise.

I am using windows authentication, I have created a username in windows, then i added the windows user in SQL management studio in security, granted "DB Read" and "DB write" and again under the database security tab. still from the web authentication fails. i must be nissing a step or two?

I expect to set up a username for each database as i setup new customers.

View 1 Replies View Related

Data Access :: Users Get Wrong Data Records - Cross Coupling When Accessing Files From MVC App

Aug 7, 2015

I have an MVC asp.net application that stores many records in a table on sql server, in its own system.  used the system for 2 months, worked fine accessing, changing data.

Now that other users are logging in? there is cross coupling going on.  one user gets the data from another users sql search.

In the mvc app it had used the get async method to read the ID record from the db, i set that to synchronous.  no effect;  the user makes their own login id but that does nt matter either.

View 8 Replies View Related

Exporting And Importing Sql Server Data Programmatically

Mar 12, 2008

I have a web application I created in asp.net + sql2005 and am deploying a genercized version of it to multiple clients. I have created a script which dynamically generates a database to a server and creates all of the tables, procs, and views. I now need data from the old database, which will be imported into the new database. It's basically default users, lookup values, etc. What are some methods of getting this data out of the old server and into the new server? I was thinking about generating flat files with the data, then writing code to loop through and insert the data, but it seems very tedious. Do I have any other options? I cannot use Backup and Restore because I have no access to the new sql server's filesystem.Thanks. 

View 3 Replies View Related

Programmatically Remove Varbinary Data From Table

Mar 29, 2008

Hey all,
I have a profile table for members of a website that allows them to upload an avatar for use throughout the site. I decided to add the option to just remove the avatar if they want to no longer use one at all and I am stuck.
I am running an update statement against thier entire profile incase they change more then just removing thier avatar but of course when I try this statement.
myCommand.Parameters.AddWithValue("@avatar", "")
I get a conversion error, which makes sence. So what instead of "" do I need for code to just insert empty data to overwirte thier current avatar data.
Any help would be great, thanks for you time.

View 5 Replies View Related

Programmatically Move Varbinary Data From One Table To Another

Apr 6, 2008

Hey all,
Another varbinary question.
I am trying to move an image stored in a table varbinary(max) directly from one table to another programmatically.
The rest of the data is just nvarchar(50) so I just use a T-SQL select statement in the code behind and feed all of the date into an SqlDataReader, I do this becuse there is some user interaction when the data is moved, so there may be some new values updated when transfering from one table to another, so once the old and possibly new data is stored in seperate variables then I use a T-SQL insert statement to move all of the data into the other table.
Problem is I am not really sure how to handle the image data(varbinary(max)) to just do a straight up transfer from the one table to another. I get conversion errors when trying to handle the data as a string which makes sense.
Not sure what to put for code examples since I really am stumped with this, but here is what is not working.
Dim imageX As String
SqlDataReader Code - imageX = reader("imageData")
Insert code - myCommand.Parameters.AddWithValue("@imageData", imageX)
Thanks in advance,

View 6 Replies View Related

Programmatically Data Conversion Component Creation

Jan 9, 2007

Hi there,

I have created a package which simply imports data from a flat file to a SQL Server table. But I need to incorporate a data conversion component by which I may change the source-destination column mapping programmatically. So what I thought that I need to add a data conversion component into the dataflow task. After adding this component (I found its component id as {C3BF62C8-7C5C-4F85-83C3-E0B6F6BE267C}) I have created a path which establishes the mapping between output columns of source component and the input columns of data conversion component. Now I am not sure how to establish the mapping between the data conversion component€™s input column collection and output column collection.

I am giving my code snippet here,
IDTSComponentMetaData90 sourceDataFlowComponent = dataFlowTask.ComponentMetaDataCollection.New();
sourceDataFlowComponent.ComponentClassID = "{90C7770B-DE7C-435E-880E-E718C92C0573}";
€¦ €¦ €¦. // Code for configuring the source data flow component

IDTSComponentMetaData90 conversionDataFlowComponent = dataFlowTask.ComponentMetaDataCollection.New();// creating data conversion
conversionDataFlowComponent.ComponentClassID = "{C3BF62C8-7C5C-4F85-83C3-E0B6F6BE267C}";// This is the GUID for data conversion component
CManagedComponentWrapper conversionInstance = conversionDataFlowComponent.Instantiate();//Instantiate
conversionInstance.ProvideComponentProperties();
// Now creating a path to connet the source and conversion
IDTSPath90 fPath = dataFlowTask.PathCollection.New(); fPath.AttachPathAndPropagateNotifications(
sourceDataFlowComponent.OutputCollection[0],
conversionDataFlowComponent.InputCollection[0]);
// Sould I need to accuire connect for data conversion? Im not sure
conversionInstance.AcquireConnections(null);
conversionInstance.ReinitializeMetaData();
// Get the input collection
IDTSInput90 input = conversionDataFlowComponent.InputCollection[0];
IDTSVirtualInput90 vInput = input.GetVirtualInput();
foreach (IDTSVirtualInputColumn90 vColumn in vInput.VirtualInputColumnCollection){
conversionInstance.SetUsageType(
input.ID, vInput, vColumn.LineageID, DTSUsageType.UT_READONLY);
}

.. . // Well here I am stucked. What I need to do here to establish a map
// between conversionDataFlowComponent.InputCollection[0] and
// conversionDataFlowComponent.OutputCollection[0]?


As you can see I am just away from creating the mapping between input and output collection. Can anybody give me an idea how can I achieve this?

I will appreciate all kind of suggestions and comments.

Regards
Moim

View 11 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved