Command parameters, DBNull and SQL Server image field
Hi!
This code (using the System.Data.SqlClient namespace)...
SqlCommand c = myConnection.CreateCommand();
c.CommandText = "INSERT INTO myTable (myField) VALUES (@myParameter)";
c.Parameters.Add("@myParameter", myValue);
c.ExecuteNonQuery();
...usually works perfectly fine for all kinds of myFields and all
kinds of myValues, UNLESS
- myField is of (SQL Server) data type "image" AND
- myValue is DBNull.Value
In that case I get an SQL Server error message stating that nvarchar
is incompatible with image ("Operandentypkollision: nvarchar ist
inkompatibel mit image").
I think I understand what is happening behind the scenes: ADO.NET
cannot infer a useful data type from DBNull.Value so it assumes that
it's an nvarchar, which supports implicit conversion into a lot of
other data types, excluding (unfortunately) image.
Is there an easy solution to this problem? I need this for a library
function, i.e. the data type of myField is not known at run-time. Of
course, I could string-replace @myParameter with NULL if myValue is
DBNull.Value but that seems like a rather ugly workaround to me...
Greetings,
Heinzi
PS: I'm using .net 1.0/1.1. Tag: LDAP: User associate to computer Tag: 140667
Responding to DataGrid selection
With a .Net 2's WinForms which contain
1) a DataGrid which is assigned to a DataSet's DataTable (some columns are
"hidden" on screen)
2) a few TextBox which are aligned to different fields within the same
DataTable
What event do I code for the .Net DataGrid such that the TextBoxes's value
are updated as different rows are selected? Tag: LDAP: User associate to computer Tag: 140666
update db ?
I am having an issue with getting my ds to update my db. I am pulling info
from the NW db on my Default.aspx page. I then click the edit btn and pass
the data to my Details.aspx page. That works fine. The issue is getting the
ds to actually update the db. I know this is simple, but I can't seem to
figure out what I am doing wrong.
Here is the code... please don't laugh to hard, as this is the first time
that I have tried to do this with code-behind, I normally just use a SqlDS on
the page, but want to make the page look cleaner...
Protected Sub dvDetails_ItemUpdating(ByVal sender As Object, ByVal e As
DetailsViewUpdateEventArgs) Handles dvDetails.ItemUpdating
Dim connStr As String =
ConfigurationManager.ConnectionStrings("NWConnectionString").ToString()
Dim conn As New SqlConnection(connStr)
'Dim strSql As String = "SELECT * FROM Employees WHERE
EmployeeID=@EmployeeID"
Dim upSql As String = "UPDATE Employees SET LastName=@LastName,
FirstName=@FirstName, Title=@Title, Address=@Address," & _
"City=@City, Region=@Region, PostalCode=@PostalCode,
HireDate=@HireDate WHERE EmployeeID=@EmployeeID"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim ds1 As New DataSet
Dim upCmd As New SqlCommand(upSql, conn)
Dim idParam As SqlParameter = upCmd.Parameters.Add("@EmployeeID",
SqlDbType.Int, 4, "EmployeeID")
Try
' da.SelectCommand = New SqlCommand(strSql, conn)
'da.Fill(ds, "Employees")
upCmd.Parameters.Add("@LastName", SqlDbType.VarChar, 20,
"LastName")
upCmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 10,
"FirstName")
upCmd.Parameters.Add("@Title", SqlDbType.VarChar, 30, "Title")
upCmd.Parameters.Add("@Address", SqlDbType.VarChar, 60, "Address")
upCmd.Parameters.Add("@City", SqlDbType.VarChar, 15, "City")
upCmd.Parameters.Add("@Region", SqlDbType.VarChar, 15, "Region")
upCmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10,
"PostalCode")
upCmd.Parameters.Add("@HireDate", SqlDbType.DateTime, 8,
"HireDate")
idParam.SourceVersion = DataRowVersion.Original
conn.Open()
'Update Employees Table
ds1 = ds.GetChanges(DataRowState.Modified)
da.Update(ds1)
ds.Merge(ds1, False, MissingSchemaAction.Add)
ds.AcceptChanges()
dvDetails.DataBind()
Catch ex As Exception
'Display Error
Console.WriteLine("Error: " & ex.ToString())
Finally
'Close Connection
conn.Close()
'Redirect to Home
Response.Redirect("~/Default.aspx")
End Try
End Sub
As this is for learning purposes only, if you could please let me know what
needs to be changed and the format of the actual update that would be great.
I want to start using this on a normal basis, but really want to understand
it before putting it into a live app.
Thanks Tag: LDAP: User associate to computer Tag: 140651
Indexing usefull or not??
Maybe a stupid one,......
is it still usefull to make indexes on the SQL server since in ADO.NET we
work with complete datasets which contain complete or parts of tables???
--
Best regards
Luc N Tag: LDAP: User associate to computer Tag: 140650
Problems in loading data from an access database into an array
Please i'm new in VB.net and i'm designing a Cinema booking and purchase
system..I need to load the seat ID from the database into an array.please
how do i go about it.. or can anyone give me an idea of how i can show seats
are availabele,booked or bought..i'll really appreciate input....
regards
wale fabiyi
Kuala Lumpur,Malaysia Tag: LDAP: User associate to computer Tag: 140644
Requesting some help
Hello community
I am scincerley asking for some help. I'm 31 years old and live in the UK,
I'm married with two children and have worked all my life as has my wife.
I have been given an opportunity to emigrate to Canada and start a life long
ambition in my chosen career I have a problem though. We cannot raise the
money to move and have no deposit for a home, without this we cannot go.
Its a long shot but all I ask is if someone out there would be kind enough
to give my family a £1 donation.
I don't know if what I'm doing is allowed but if nobody wants to give then
there is no harm in asking
If your happy to help then email at d2801@yahoo.com and 'll send you my
details
Kind regards Dave Tag: LDAP: User associate to computer Tag: 140643
Merge DataRow Items?
I have a DataTable with one row and I did a Merge() from another
DataTable and now I have two rows. How can I get the rows to be a
single row (assuming row 0 is the "dominant" one).
Thanks. Tag: LDAP: User associate to computer Tag: 140642
Null value Check in DataTable?
I have a DataRow in a DataTable. I want to know if there is a value. I
do this
if ( this.Rows[0]["Col_A"] == null )
{
throw new Exception ( "no" );
}
However this condition is never hit. Why?
Thanks. Tag: LDAP: User associate to computer Tag: 140640
DataAdapter.Update() returns error.
Hi,
I am populating a dataset from a stored procedure, which returns
multiple resultsets. One of the resultset is formed with a join
condition from two tables. I am updating the fields of the
respective
datatable. Then update the first table in the database using
DataAdapter.Update(). This succeeds. Subsequently, I update the
fields of the second table in the datatable and update the
respective(second) table in the database using DataAdapter.Update().
This throws the error, "Concurrency violation: the UpdateCommand
affected 0 of the expected 1 records.". Dataset.HasChanges() returns
true before each update. I give below the code.
// First Table
DataRow dr = dtOrderInfo.Rows[iSelectedRow];
dr.BeginEdit();
// Data Row changes.
...
...
dr.EndEdit();
// connect to database and execute as follows.
cnDatabaseOpen(strdbconnect);
SqlDataAdapter da = new SqlDataAdapter("Select top 0 * from
OrderDetail", cnDatabase);
SqlCommandBuilder scb = new SqlCommandBuilder(da);
da.Update(dtOrderInfo);
da.Dispose();
cnDatabaseClose();
// Second Table
dr = null;
dr = dtOrderInfo.Rows[iSelectedRow];
dr.BeginEdit();
// Data Row changes.
...
...
dr.EndEdit();
// connect to database and execute as follows.
cnDatabaseOpen(strdbconnect);
SqlDataAdapter da = new SqlDataAdapter("Select top 0 * from Orders",
cnDatabase);
SqlCommandBuilder scb = new SqlCommandBuilder(da);
// Following line throws error.
da.Update(dtOrderInfo);
da.Dispose();
cnDatabaseClose();
I get the error in da.Update() for the second table.
Any help would be greatly appreciated.
Thanks
Manohar Tag: LDAP: User associate to computer Tag: 140639
Unexplained entry in Oledb Excel schema table
Hi
I have an excel workbook with 4 worksheets. When I connect to this workbook
using an Oledb connection, I use GetOleDbTableSchema to retrieve the names of
the worksheets ("TABLE_NAME"), only the schema table returns 5 rows, not 4.
If my worksheet names are Sheet1, Sheet2, Sheet3 and Sheet4, I would expect
to get 4 rows in the schema datatable, with "TABLE_NAME" as Sheet1$, Sheet2$,
Sheet3$ and Sheet4$, however, I get those four, and an extra one, say
Sheet1$_
Has anyone come across this before who could offer either an explanation, or
a solution, or preferably both?
Thanks in advance for your help. Tag: LDAP: User associate to computer Tag: 140632
How to get the primary key
Hello there,
I want to write a function returning the primary key name of a certain
table.
The following function successfully returns the names of all fields of
a table:
public string[] GetFieldNames(string tableName)
{
string[] fieldNames = null;
IDbConnection conn = _factory.CreateConnection(true);
try
{
string[] restrictions = { null, tableName, null };
DataTable dataTable = (conn as
DbConnection).GetSchema("Columns", restrictions);
if (dataTable != null)
{
fieldNames = new string[dataTable.Rows.Count];
for (int i = 0; i < dataTable.Rows.Count; i++)
fieldNames[i] = dataTable.Rows[i]
["COLUMN_NAME"].ToString();
}
return fieldNames;
}
finally
{
conn.Close();
}
}
An interesting part in the upper function is, that the table name is
at the second position in the restrictions array instead on the third,
as I have seen several times in samples found in the internet. In my
case I get the field names with the table name at the second position
in the array.
Now I wrote a function to get the primary key of a table:
public string GetPrimaryKeyName(string tableName)
{
IDbConnection conn = _factory.CreateConnection(true);
try
{
string[] restrictions = { null, tableName,
tableName };
DataTable dataTable = (conn as
DbConnection).GetSchema("PrimaryKeys", restrictions);
if (dataTable != null)
{
if (dataTable.Rows.Count > 0)
return dataTable.Rows[0]
["COLUMN_NAME"].ToString();
}
return null;
}
finally
{
conn.Close();
}
}
That function never returns me the primary key, regardless on which
position the table name is in the restrictions array. I heard that the
upper function does not work for connections based on Oracle. Is that
true?
Regards,
Norbert Tag: LDAP: User associate to computer Tag: 140630
How to get the last created or modified dataset
Hello,
is there a possibility to get the ID of the last created or modified
dataset of a table via ADO.NET? Is there a database independent way?
In SQL Server you can call the scope_identity() function, but this
won't work in Oracle, MySQL, Access a.s.o.
Thanks in advance,
Norbert Tag: LDAP: User associate to computer Tag: 140628
TransactionScope promotion & isolation levels
Our project is using the System.Transactions.TransactionScope class to
provide an ambient transaction which our DAL classes can leverage.
I'm looking for some information about the TransactionScope class to answer
a few questions about how it behaves when a transaction is promoted to a
distributed transaction.
Our environment is ASP.NETv2 on Win2003 calling db server running SQL2005.
In pseudo-code, we do something like this:
Using (scope1 = New TransactionScope())
DalA.IssueInsertAndUpdateStatementsToDb1()
Using (scope2 = New TransactionScope(TransactionScopeOptions.Suppress))
DalB.IssueInsertToDb2()
scope2.Complete()
End Using
scope1.Complete()
End Using
The first TransactionScope is used to create a transaction for a series of
DAL inserts and updates to our primary database. Then we start a second,
nested scope with the transaction option set to "Suppress" and it is used to
insert a record into a second database (on the same db server).
Both databases are configured for a default isolation level of
ReadCommitted, but we are seeing some transactions come across at the
Serializable isolation level.
My question is: is the Serializable isolation level being caused by the use
of TransactionScope (and its implicit use of DTC)?
If we were to provide the appropriate TransactionOption class to the
constructor of each scope object, would it provide us with ReadCommitted
isolation level, or does the use of DTC always force the use of Serializable?
Thanks,
Chris Tag: LDAP: User associate to computer Tag: 140627
DataReader values and .ToString
Hello,
In order to avoid errors, I have all my DataReader-fields converted with a
.ToString.
This in case some record could have Null-fields and an error would be
thrown.
This works fine, except for "money" fields in SQL-Server.
When I enter e.g. ? 2,50 and I read it back with a DataReader without
.ToString, I get the correct display.
However using .ToString, I get no valuta-sign and the value is multiplied by
10 000.
When trying to StringFormat the DataReader.ToString, I get a syntax error.
Can someone explain this to me an offer some help?
Many thanks and greetings,
Michel Tag: LDAP: User associate to computer Tag: 140619
SqlDependency.Start KeyNotFoundException - Possible Bug
I'm working heavily with query notifications in SQL Server 2005 and I'm now
getting the following exception:
System.Collections.Generic.KeyNotFoundException: The given key was not
present in the dictionary.
This was working for quite a while and then it stopped. At first, the
exception was intermittent, but now it's permanent. The exception is
happening deep inside of a System.Data.dll in a class called
SqlDependencyProcessDispatcher in a method defined as follows:
private bool Start(string connectionString, out string server, out
DbConnectionPoolIdentity identity, out string user, out string database, ref
string queueService, string appDomainKey, SqlDependencyPerAppDomainDispatcher
dispatcher, out bool errorOccurred, out bool appDomainStart, bool useDefaults)
It looks like the method is checking a dictionary for particular key; then,
if it's found, it retrieves the item from the dictionary. Looking at
Reflector it appears that this lookup may not be threadsafe. It has a few
code blocks inside structured like this:
if (!this._sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
{
lock (this._sqlDependencyPerAppDomainDispatchers)
{
this._sqlDependencyPerAppDomainDispatchers[appDomainKey] =
dispatcher;
}
}
These should probably be using
sqlDependencyPerAppDomainDispatchers.TryGetValue instead or should move the
lock to the outside of the if statement.
No one on the Internet seems to have ever encountered this.
Two partial stack traces appear below. They're partial in that I've
ommitted a
long set of calls from our interal app framework that are orthogonal to the
problem.
The NT user making these calls is a local administrator on the database
server. The calls work a lot of the time, but break and seemingly random
moments.
We use a preconfigured SQL Server Service Broker Queue named
QueryChangeMessages and a service called QueryChangeNotifications.
Please help.
One stack trace looks like this:
[KeyNotFoundException: The given key was not present in the dictionary.]
SqlDependencyProcessDispatcher.Start(String connectionString, String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher) +0
System.Data.SqlClient.SqlDependency.Start(String connectionString, String
queue, Boolean useDefaults) +672
System.Data.SqlClient.SqlDependency.Start(String connectionString, String
queue) +7
Nvidia.PolicyInjection.CallHandlers.SqlDependencyConnection.StartInternal()
+103
[DataException: An error occurred while calling
ConfigurationManagement.Start for connection string named
ConfigurationManagement on SQL Server Service Broker Queue
QueryNotificationQueue.]
...
Another stack trace looks like this:
Server stack trace:
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.ProcessNotificationResults(SqlDataReader reader)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.SynchronouslyQueryServiceBrokerQueue()
at
SqlDependencyProcessDispatcher.SqlConnectionContainer..ctor(SqlConnectionContainerHashHelper hashHelper, String appDomainKey, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString, String&
server, DbConnectionPoolIdentity& identity, String& user, String& database,
String& queueService, String appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher, Boolean& errorOccurred,
Boolean& appDomainStart, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString, String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher)
at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle
md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type)
at SqlDependencyProcessDispatcher.Start(String connectionString, String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher)
at System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue, Boolean useDefaults)
at System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue)
... Tag: LDAP: User associate to computer Tag: 140613
SqlDependency.Start - Getting KeyNotFoundException
I'm working heavily with query notifications in SQL Server 2005 and I
get the following exception:
System.Collections.Generic.KeyNotFoundException: The given key was
not
present in the dictionary.
This was working and then it stopped. At first, the exception was
intermittent, but now it's permanent. The exception is happening deep
inside of a System.Data.dll in a class called
SqlDependencyProcessDispatcher in a method defined as follows:
private bool Start(string connectionString, out string server, out
DbConnectionPoolIdentity identity, out string user, out string
database, ref string queueService, string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher, out bool
errorOccurred, out bool appDomainStart, bool useDefaults)
It looks like the method is checking a dictionary for particular key;
then, if it's found, it retrieves the item from the dictionary.
Looking at Reflector it appears that this lookup may not be
threadsafe. It has a few code blocks inside structured like this:
if (!
this._sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
{
lock (this._sqlDependencyPerAppDomainDispatchers)
{
this._sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher;
}
}
These should probably be using
sqlDependencyPerAppDomainDispatchers.TryGetValue instead or should
move the lock to the outside of the if statement.
No one on the Internet seems to have ever encountered this.
Two partial stack traces appear below. They're partial in that I've
ommitted a
long set of calls from our interal app framework that are orthogonal
to the
problem.
The NT user making these calls is a local administrator on the
database
server. The calls work a lot of the time, but break and seemingly
random
moments.
We use a preconfigured SQL Server Service Broker Queue named
QueryChangeMessages and a service called QueryChangeNotifications.
Please help.
One stack trace looks like this:
[KeyNotFoundException: The given key was not present in the
dictionary.]
SqlDependencyProcessDispatcher.Start(String connectionString,
String queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher
dispatcher) +0
System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue, Boolean useDefaults) +672
System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue) +7
Nvidia.PolicyInjection.CallHandlers.SqlDependencyConnection.StartInternal()
+103
[DataException: An error occurred while calling
ConfigurationManagement.Start for connection string named
ConfigurationManagement on SQL Server Service Broker Queue
QueryNotificationQueue.]
...
Another stack trace looks like this:
Server stack trace:
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.ProcessNotificationResults(SqlDataReader
reader)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.SynchronouslyQueryServiceBrokerQueue()
at
SqlDependencyProcessDispatcher.SqlConnectionContainer..ctor(SqlConnectionContainerHashHelper
hashHelper, String appDomainKey, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString,
String&
server, DbConnectionPoolIdentity& identity, String& user, String&
database,
String& queueService, String appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher, Boolean&
errorOccurred,
Boolean& appDomainStart, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString,
String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher
dispatcher)
at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean
fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle
md, Object[] args, Object server, Int32 methodPtr, Boolean
fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage
msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg)
at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type)
at SqlDependencyProcessDispatcher.Start(String connectionString,
String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher
dispatcher)
at System.Data.SqlClient.SqlDependency.Start(String
connectionString,
String queue, Boolean useDefaults)
at System.Data.SqlClient.SqlDependency.Start(String
connectionString,
String queue)
... Tag: LDAP: User associate to computer Tag: 140612
GridView databinding
I have a GridView which is bound to a table. The user has the ability to
change some defaults and then run a process from this.
This all worked fine until I added in an auto postback to one of the
controls to tie in some other functionality.
After the post back, and at the end of page load complete, everything is as
it should be, but then the GridView does an automatic databind (after load
complete) and wipes it all out. Is there anyway to keep this automatic
update from occuring, or cancel it or whatever?
Thanks. Tag: LDAP: User associate to computer Tag: 140609
Database Persistance
Hi
I'm not sure whether I've given this post the correct title, but I'm a
bit unsure of where to put it.
I have a database that holds information about several of our users.
This database is stored on a central server, with an application that
periodically performs some processing, which may or may not update the
database. It is possible that some times this data will update several
times a minute.
Here's my problem - I would like to create an application, in a remote
location to the main database server that displays the database
contents. This applications would need to update its view of the
database as soon as the database changes in order to ensure that only
the most up to date information is being displayed.
I've previously done this by periodically re-reading the database and
updating the fields that have changed on screen, however as I add more
terminals, this may cause a problem. So ideally I would like a
callback or trigger to be called when the database updates that
informs the correct client, so that it can update it's screen
accordingly.
Is this possible, or am I barking up the wrong tree? Is there a better
way of doing it? I'd be very grateful if you could give me your
thoughts.
I am developing the main client application in C#, and the database is
currently MySQL. It would be possible to change the database if this
made things easier, however it would have to be a free alternative!
Many thanks
Steve Tag: LDAP: User associate to computer Tag: 140601
Detach database from SQL Server
Hello,
When I have closed my appliciation in VB.NET, and I try to detach my
database from SQL SERVER, I often get a message that the database cannot be
detachted, because it is still in use.
So I think there is some code missing in my application (in the
MDI_FormClosing?)
to make my database is no longer in use.
I already put a Connection.Close in the FormClosing also in a Finally-block
of
that FormClosing, but that does not seem to be enough.
Can someone help me with that?
Many thanks and greetings,
Michel Tag: LDAP: User associate to computer Tag: 140599
delete row from dataGridView problem
Hi All,
I have been failing to delete a row from dataGridView.
I use typed dataset.
Here is my code, please advice what wrong is here?
private void MainForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the
'lodgersDataSet1.Table_Lodgers' table. You can move, or remove it, as
needed.
this.table_LodgersTableAdapter1.Fill(this.lodgersDataSet1.Table_Lodgers);
}
private void dataGridViewLodgers_RowsRemoved(object sender,
DataGridViewRowsRemovedEventArgs e)
{
string strConnString = @"Data Source=XP\SQLEXPRESS;Initial
Catalog=Lodgers;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(strConnString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM
Table_1",sqlConnection);
MyDataSet myDataSet = new MyDataSet();
da.Fill(myDataSet, "Table_1");
// myDataSet is updated, row is deleted properly
//
DataRow dr = myDataSet.Table_1.Rows[e.RowIndex];
myDataSet.Tables["Table_1"].Rows.Remove(dr);
// Update returns 0 !!!
//
int ret = daLodgers.Update(dsLodgers2,
dsLodgers2.Tables[0].TableName);
myDataSet.Table_1.AcceptChanges();
myDataSet.AcceptChanges();
}
Thank you in advance
A. Tag: LDAP: User associate to computer Tag: 140596
ExecuteNonQuery within the loop of a datareader
Hello,
How can I use an ExecuteNonQuery within the loop of a datareader?
My code is as follows:
Dim cmdToProcess As New SqlClient.SqlCommand
Dim rdToProcess As SqlClient.SqlDataReader
With cmdToProcess
.CommandText = " SELECT * FROM tblDetails "
.Connection = cn
End With
rdToProcess = cmdToProcess .ExecuteReader
Select Case rdToProcess
Case True
Do
'here I want to add or update data
Dim cmdToChange As New SqlClient.SqlCommand
With cmdToChange
.CommandText = "INSERT INTO tblNew(AD_Action) VALUES (@Action)"
.Parameters.AddWithValue("@Action", rdToProcess("DE_Number"))
.Connection = cn
End With
cmdToChange.ExecuteNonQuery
Loop until not rdProcess.Read
End Select
At "cmdNieuweCafetariaActiedetail.ExecuteNonQuery", I get the message that I
have to close the first datareader in order to
execute, but then my code cannot proceed because rdToProcess("DE_Number")
can no longer be read.
How can I solve this?
Many thanks and greetings for your help,
Michel Tag: LDAP: User associate to computer Tag: 140594
Console and Files
How come line 1 will output garbage to the screen, but line 2 will output a
good number to a file?
How can I make line 1 out put a good number to the screen
String* dayStr = System::DateTime::Now.ToString("dd");
Int32 dayInt = System::Int32::Parse(dayStr);
Console::WriteLine("the day is {0}", __box(dayInt) ); // Line 1
.
.
.
String* path = new String("_1D.txt"); // will read the time from a file
FileStream * fs = new FileStream(path, FileMode::Open);
BinaryReade* br = new BinaryReader(fs);
Int32 day = br->ReadInt32();
fs = new FileStream(S"_1k.txt", FileMode::Create); //will write the time to
another file
BinaryWriter* bw = new BinaryWriter(fs);
Br->Write( day);
//Line 2 Tag: LDAP: User associate to computer Tag: 140587
encrypt/decrypt function in asp.net 2
i am looking for code sampe in aso.net 2 for encrypt/decrypt
of paswr d withought using any external DLL (judt to use existing net2 tools)
thnaks i nadvance
peleg Tag: LDAP: User associate to computer Tag: 140586
SqlDependency.Start - Getting intermittent KeyNotFoundException
I'm working heavily with query notifications in SQL Server 2005 and I
intermittently get the following exception:
System.Collections.Generic.KeyNotFoundException: The given key was not
present in the dictionary.
No one on the Internet seems to have ever encountered this.
A partial stack trace appears below. It's partial in that I've ommitted a
long set of calls from our interal app framework that are orthogonal to the
problem.
The NT user making these calls is a local administrator on the database
server. The calls work a lot of the time, but break and seemingly random
moments.
We use a preconfigured SQL Server Service Broker Queue named
QueryChangeMessages and a service called QueryChangeNotifications.
Please help.
Server stack trace:
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.ProcessNotificationResults(SqlDataReader reader)
at
SqlDependencyProcessDispatcher.SqlConnectionContainer.SynchronouslyQueryServiceBrokerQueue()
at
SqlDependencyProcessDispatcher.SqlConnectionContainer..ctor(SqlConnectionContainerHashHelper hashHelper, String appDomainKey, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString, String&
server, DbConnectionPoolIdentity& identity, String& user, String& database,
String& queueService, String appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher, Boolean& errorOccurred,
Boolean& appDomainStart, Boolean useDefaults)
at SqlDependencyProcessDispatcher.Start(String connectionString, String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher)
at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle
md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext,
Object[]& outArgs)
at
System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type)
at SqlDependencyProcessDispatcher.Start(String connectionString, String
queue, String appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher)
at System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue, Boolean useDefaults)
at System.Data.SqlClient.SqlDependency.Start(String connectionString,
String queue) Tag: LDAP: User associate to computer Tag: 140578
Internal .Net Framework Data Provider error 6.
Hi
I'm getting very occasional exceptions in an application when trying
to open a SQLConnection. Does anyone know what this error means, or
what I can do about it? The error has only occurred a couple of times,
each time with a gap of more than a day, so I cannot replicate or even
find a pattern other than it happening at the point where I open the
connection.
I've pasted the exception details below.
Thanks
Dan
----------------------
Source:
System.Data
Message:
Internal .Net Framework Data Provider error 6.
Stack:
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) at
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory) at
System.Data.SqlClient.SqlConnection.Open() at.... etc....
Type:
System.InvalidOperationException Tag: LDAP: User associate to computer Tag: 140577
Problem in datagrid paging and checkbox
Hi All,
I have one issue in using the datagrid in the asp.Net. I
have the checkbox column in the datagrid. And also having the paging
option.I have selected two items in the page 1 and navigate to page
2.And i selected 1 item. The problem is when i come back to page
one ,all the item was unchecked.Cos during the paging i need to bind
the grid again from the database .Is there any way to bind the
datagrid with one time data fetch from database. Tag: LDAP: User associate to computer Tag: 140571
BackgroundWorkers and ADO.Net
I have an app that allows the user to build a query and then click on a
button to execute the query and the results are then used to fill a grid.
Can I have the retrieval run in a backgroundworker and have a button that
would allow the user to cancel the query if it is running for too long of a
period? Is the BackgroundWorker able to populate a grid which is running in
the primary thread?
Bill Tag: LDAP: User associate to computer Tag: 140569
Automatic filling fields
Hi guys,
could you please help me on my problem.
>>>> --------------- <<<<<<<<<
Datasource: MS Access 2003
Table1: Tbl_Employee
Field1: Emp_name
Field2: Position
Field3: Contact#
Field4: Address
Table2: Tbl_Salary
>>>> --------------- <<<<<<<<<
Windows Form of Visual Basic.net
i have a field Employee on the form, the problem is, i when i type the name
of employee, i want the position, contact# and address to automatically fill
my other fields and will save on my database Tbl_Salary.
--
Message posted via DotNetMonster.com
http://www.dotnetmonster.com/Uwe/Forums.aspx/dotnet-ado-net/200707/1 Tag: LDAP: User associate to computer Tag: 140566
ObjectDataSource a little help
I have something that works, but it only returns one row of data when i
create an ObjectDataSource with it and bind it to a gridview so i need a
little help with this (thanks)
as simple as it gets
1. my class:
Imports Microsoft.VisualBasic
Public Class radioShowFiles
Private _szFileName As String
Public Property szFileName() As String
Get
Return _szFileName
End Get
Set(ByVal value As String)
_szFileName = value
End Set
End Property
End Class
2.
the functions that allows it to bind:
Public Function fn_getallRadioShows() As DirectoryInfo
Dim ri As System.IO.DirectoryInfo = New
System.IO.DirectoryInfo("c:\websites\arlnewlook\radioshows")
Return ri
End Function
Function fn_rtn() As radioShowFiles
Dim rsf As radioShowFiles = New radioShowFiles
Dim ri As DirectoryInfo = Me.fn_getallRadioShows
Dim diar1 As IO.FileInfo() = ri.GetFiles()
Dim dra As IO.FileInfo
For Each dra In diar1
rsf.szFileName = dra.Name
Next
Return rsf
End Function
End Class
I know why it's only including the last row of data, but i am sorry to say i
don't know what to do to change it! I know i'm very close.
THANKS!
KES
--
Share The Knowledge. I need all the help I can get and so do you! Tag: LDAP: User associate to computer Tag: 140565
combining datasets
Hi,
I have 2 datasets right now, say with the following structure:
DataSet 1 has a row called ItemCode, index 1
DataSet 2 has a row called ItemCode, index 1
both are similar, but i need to merge them to make one dataset, which
needs to have everything in DataSet1 plus anything from DataSet2
that's not in DataSet1 already. I'm not too familiar with working
with Datasets, i know theres suppose to be a way to join them, can
someone help out? Both have a ItemCode which is what needs to be used
to make sure no duplicates from DataSet2 get into DataSet1.
Thanks. Tag: LDAP: User associate to computer Tag: 140563
DataAdapter with Parameter problem
When I run the following code everything works fine (which proves the =
stored procedure and the parameter:
Dim cmdSQL As New SqlCommand
cmdSQL.CommandType =3D CommandType.StoredProcedure
cmdSQL.CommandText =3D "bdl_CustomerOrders_SELECT"
cmdSQL.Connection =3D mcnnSQL
Dim prm As New SqlParameter()
prm.ParameterName =3D "@CustomerID"
prm.Value =3D Me.cboCustomerSELECT.SelectedValue
prm.Direction =3D ParameterDirection.Input
cmdSQL.Parameters.Add(prm)
mcnnSQL.Open()
Dim dr As SqlDataReader
dr =3D cmdSQL.ExecuteReader()
While dr.Read
Debug.WriteLine(dr.Item(0).ToString)
End While
dr.Close()
However, when I run the following code I get the error message:
Incorrect syntax near 'bdl_CustomerOrders_SELECT' at the last line: =
sda.Fill(ds, "CustomerOrders")
Thoughts anyone ?
Dim sda As New SqlDataAdapter("bdl_CustomerOrders_SELECT", mcnnSQ=
L)
Dim prm As SqlParameter =3D =
sda.SelectCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, =
"CustomerID")
prm.Direction =3D ParameterDirection.Input
prm.SqlValue =3D Me.cboCustomerSELECT.SelectedValue
sda.TableMappings.Add("Table1", "CustomerOrders")
Dim ds As New DataSet()
sda.Fill(ds, "CustomerOrders")
Des
-- =
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ Tag: LDAP: User associate to computer Tag: 140562
Question about TransactionScope
Hi,
Does TransactionScope need DTC in situations that the transaction is not
distributed?
I have a set of non-distributed transactions and I am not sure that
TransactionScope is the best option for best practice perspective.
Thank you,
Max Tag: LDAP: User associate to computer Tag: 140560
Strongly Typed DataSet -> Preview Data -> How to preview stored procedures with GUID parameter?
Hi,
In Strongly typed datasets, when we preview a table adapter query, we cannot
preview a stored procedure query that has GUID parameter.
The error complains that cannot convert a string to GUID.
What is the proper format for GUID parameters? Of course I tried {.} format.
Thanks,
Max Tag: LDAP: User associate to computer Tag: 140556
Typed DataSets ADO.NET 2.0
For a project I have a typed dataset created ( by dragging tables/
views and configuring the appropriate queries ).
If the database schema for these tables is changed (e.g. few columns
get added), is it possible to automatically refresh the DataSet.
Right now, I see that the Fill query only has the previous columns
selected, the new added ones do not appear.
This is my first time using datasets, so wondering if the adapter
queries can be refreshed somehow.
Thanks. Tag: LDAP: User associate to computer Tag: 140553
Check user input data exist in database: ERROR
Dim retVal As Boolean = False
Dim cnSQL As SqlConnection
Dim cmSQL As SqlCommand
Dim strSQL As String
strSQL = "Select * From Table_Contacts where EmailAddress = '" &
txtEmail.Text & "' OR Name = '" & txtName.Text & "';"
cnSQL = New SqlConnection(thisConnection)
cnSQL.Open()
cmSQL = New SqlCommand(strSQL, cnSQL)
Dim reader As SqlDataReader = cmSQL.ExecuteReader()
If Not reader.HasRows Then
retVal = False
MessageBox.Show("No Record")
Else
MessageBox.Show(" already exists!", " ", MessageBoxButtons.OK,
MessageBoxIcon.Error)
retVal = True
End If
cnSQL.Close()
cmSQL.Dispose()
cnSQL.Dispose()
retVal = True
Can someone help me with this?
I'm keep getting "already exist" even there is no matching record in the
database.
- Thanks Tag: LDAP: User associate to computer Tag: 140546
Help with this Argument 'Prompt' cannot be converted to type 'Stri
Hi;
I am creating a windows app using ado.net 2.0 in the app I am connecting to
a database by creating and then using a data provider factory.
When I call sqlConn.Open() I get the follwoing message "Argument 'Prompt -
cannot be converted to type String".
What am I missing in my code ?
My code follows:
Here are the entries in my app.config file
<configuration>
<appSettings>
<add key="provider" value="System.Data.SqlClient" />
</appSettings>
<connectionStrings>
<add name ="cnStr" connectionString =
"Data Source=aServer;integrated Security=True;initial Catalog=GoodTable" />
</connectionStrings>
</configuration>
Here is how I call this in my app. :
Try
Dim sAttr As String = ConfigurationManager.AppSettings("provider")
' Dim dp As DataProvider =
CType(Enum].Parse(GetType(DataProvider),sAttr), DataProvider)
Dim cnStr As String =
ConfigurationManager.ConnectionStrings("cnStr").ConnectionString
' Create the provider factory
Dim df As DbProviderFactory =
DbProviderFactories.GetFactory(sAttr)
'Connection here
Dim sqlConn As DbConnection = df.CreateConnection()
sqlConn.ConnectionString = cnStr
Catch ex As Exception
MsgBox(ex)
End Try
Try
sqlConn.Open()
Catch ex1 As Exception
MsgBox(ex1)
End Try
Thanks for any suggestions !
--
Gordon Tag: LDAP: User associate to computer Tag: 140545
What are the pros and cons in using Enterprise Library?
I'm new to .net. It seems that those application blocks in Enterprise
Library are very useful especially when one tries to build a new application.
I want to know the pros and cons in using those blocks. Is MS going to
release new Enterprise Library for future .net version/build? If I use the
current version of the blocks, what happen when a new version comes out? Tag: LDAP: User associate to computer Tag: 140544
NULL GUID fields in a Nested Query
Hi there,
Firstly, I hope this is in the right place!
I have a problem with a nested query I am generating at runtime.
My table (tblIndexValue) has values in every cell in all rows including the
createdUserID column. The createdUserID's datatype is a GUID, and the table
is in Access using Jet 4 to connect from .NET.
Here is the query, as captured in the immediate window: -
SELECT DocumentID,
(SELECT value FROM tblIndexValue WHERE
indexFieldID={7b47a555-9a8e-4336-acbf-12b170d46f71} AND
departmentID={f7d75dd6-096c-43e1-9f25-285fbe74a547} AND
DocumentID=Q.DocumentID) AS IV1,
(SELECT createdUserID FROM tblIndexValue WHERE
indexFieldID={7b47a555-9a8e-4336-acbf-12b170d46f71} AND
departmentID={f7d75dd6-096c-43e1-9f25-285fbe74a547} AND
DocumentID=Q.DocumentID) AS IVID1
FROM tblDocument AS Q
GROUP BY Q.DocumentID;
IV1, i.e. the value field (a text value) displays fine. However, IVID1, the
createdUserID file (a GUID) only shows NULLS. If I run the inner query on
it's own (i.e. SELECT createdUserID FROM .... substituting the Q.DocumentID
for any of my documentID GUIDs) it displays as expected.
Have I missed something here?
Many thanks,
David Tag: LDAP: User associate to computer Tag: 140539
Flummoxed by Connection Problem
Everything was working fine until suddenly this problem appeared from
nowhere:
Boot up the pc and go into SQL Server Management Studio. The database is
present and the data can be accessed.
Go into VB2005 Express and run the project. Everything works fine.
Open Database Explorer and connect to the database and the following
happens:
1. The project no longer works and this error appears at cnn.open()
'Cannot open user default database. Login failed. Login failed for user'
2. The database is no longer available in Management Studio. It appears
but no longer has the little + sign next to it and the data is no longer
accessible. If I try and view the database properties I get this error:
Cannot show requested dialog.
ADDITIONAL INFORMATION:
Cannot show requested dialog. (Microsoft.SqlServer.Express.SqlMgmt)
An exception occurred while executing a Transact-SQL statement or batch.
(Microsoft.SqlServer.Express.ConnectionInfo)
Database 'T:\VS_DATA\NORTHWND.MDF' cannot be opened due to inaccessible
files or insufficient memory or disk space. See the SQL Server errorlog
for details. (Microsoft SQL Server, Error: 945)
The only way I can get out of this situation is to reboot my pc. I am ok
as long as I don't try and connect to the database via Database Explorer.
I have tried disconnecting from and even deleting the database in Database
Explorer to no avail. HELP!
Des
--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ Tag: LDAP: User associate to computer Tag: 140536
Computed Field In Typed Dataset
I have a list box that is bound to an object data source. I added a column,
say ColumnC, to my typed data set (using the designer) and for the expression
property I entered
ColumnA + ': ' + ColumnB
When I preview the data in the designer I get exactly what I want.
Now I go over to the object data source on my web page, refresh it and
refresh the schema. I can now see ColumnC as an option for the list box's
data text field. However, when I run the page nothing shows up in the list
box. However, when I view the page source, I see that the data value field
did render.
Next I put in a value (instead of the default DBNull) for the DefaultValue
property. After going through the whole exercise of refreshing and such
again, I run the page and the default value I put in is returned in the list
box.
Does anyone know what I missed? It must be something stupid.
Thanks ... Tag: LDAP: User associate to computer Tag: 140531
!VB.NET/Access: OleDbException (Data type mismatch in criteria expression)
Dear ADO.NET experts!
I hope someone can help me, as I've been tearing my hair out with this one
all day!
I'm getting very odd "Data type mismatch in criteria expression" errors that
I can absolutely not nail down or debug at all.
SCREENSHOT:
http://img384.imageshack.us/img384/6564/oledbexceptionwb5.jpg
Using: VB.NET (2005/.NET 2.0 & MS Access (2000) MDB)
Process: This is a Wizard to make a monthly tax return. The user selects a
date from a pre-filled drop-down combo box and clicks "Next" to go to the
next page of the Wizard which loads payments (grouped by supplier) from the
Payments table into a DataGridView. The tableadapter fill method is called,
passing the From and To dates which are used to determine which payments are
shown in the DataGridView on the next page.
---
SQL (taken from the command property of the dataset designer):
SELECT Subcontractor_ID, SUM(Gross) AS Gross, SUM(DirectCostOfMaterials0dp)
AS DirectCostOfMaterials0dp, SUM(TotalAmountDeducted) AS
TotalAmountDeducted, SUM(Net) AS Net
FROM Payment
WHERE (PaymentDate >= ?) AND (PaymentDate < ?) AND (Company_ID = ?) AND
(MonthlyReturn_ID IS NULL OR MonthlyReturn_ID = '')
GROUP BY Subcontractor_ID
CODE:
' A tax month is from the 6th to the 5th of the following month
_FromIncDate = DateAdd(DateInterval.Day, 1, DateAdd(DateInterval.Month, -1,
CDate(cboMonthlyReturnPeriod.Text)))
_ToDate = DateAdd(DateInterval.Day, 1, CDate(cboMonthlyReturnPeriod.Text))
' Crashes on this line
taPayments.FillForNewMonthlyReturn(DsInvoice1.Payment, _FromIncDate,
_ToDate, My.Settings.CurrentCompany_ID)
---
I have checked, double-checked and re-checked the data
The table columns are defined as "DateTime" in Access, "DateTime" in the
DataSet designer, and the values passed as parameters to the .Fill function
are .NET Dates.
This fault only happens on one customer's database, although this database
appears to be no different to any of the other databases.
I had thought perhaps this was to do with regional settings, but cannot find
any evidence for this.
What can I do to prevent this from occurring, and how can I debug the
OleDbException to find out precisely what column the type mismatch is
referring to?
Warm Regards,
Mike Wilson
P.S. How does one go about subscribing to the Microsoft
privatenews.microsoft.com newsgroups? We have an MSDN Subscription, but the
links from the MSDN Subscriber Downloads page take you round in circles...
(also x-posted to: microsoft.public.dotnet.languages.vb.data - but forgot to
add this group) Tag: LDAP: User associate to computer Tag: 140530
Ado.net and SQl view ???
Dear all,
I would like to bind a datgrid control to an SQL view.
How set SQL command type for a view ? Is it Text ?
IN which form the sql view is returned, data set ?
When I get my view bind to my grid, if new data is inserted in my database,
does my view will be automatically refreshed with new data or dor I have to
run the refresh my self with my datagrid ?
The idea is that I would like that my grid data gets automatically updated
if new data gets inserted and remove from my tables manged by the view
thnaks for help
regards
serge Tag: LDAP: User associate to computer Tag: 140529
Sending a set of data to a stored procedure
Hello
I need to write a stored procedure that executes a bunch of bulked and
related(stock) trades. For example, the customer may have requested four
trades to be placed. The trades are related because the money from selling
one stock say needs to fund a new stock purchase.
What is the recommened approach for sending the set of information to my
stored procedure please? I can'r rely on stored proc parameters because the
number of bulk trades varies and can be quite large.
We have thought of two possible approaches:
1. Send a delimited string with special characters in the string signalling
the begining of a new trade instruction. Clearly the stored proc is going to
be complicated because of the string handling it is going to have to do
2. Insert the trade instructions into a temporary table and have the trade
execution stored read the data from it during from its execution
The target database is Sybase.
Thanks
Amir Tohidi Tag: LDAP: User associate to computer Tag: 140525
Syntax error in INSERT INTO statement. vb.net
I am using VB.net
The Error message is :Syntax error in INSERT INTO statement. vb.net
Could this be casused by my primary Key? if my primary key is "ID" and it is
(autonumber). I tried inseting a blank field, number in a field, and the
example is with out the field at all.
INSERT INTO EST_TRI_Target_Data (TRI Facility ID, Facility Name, Street
Address, City, State, Zip Code, County, Parent Company, Parent Company Duns,
Mailing Name, Mailing Street Address, Mailing City, Mailing State, Mailing
Zip Code, Public Contact Name, Public Contact Phone, Tech Contact Name, Tech
Contact Phone, Tech Contact Email, Major Industry, Primary SIC Code) VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
This is the code
Dim myConnection2 As New _
OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Documents and Settings\BookPC\My Documents\EST ltd USA\TRI
data\TRI_data.mdb")
'Dim mySqlDataAdapter As SqlDataAdapter
Dim strSelect2 As String = _
"SELECT * FROM EST_TRI_Target_Data"
Dim dsCmd2 As _
New OleDbDataAdapter(strSelect2, myConnection2)
'myConnection2 = New SqlConnection("server=(local)C:\Documents and
Settings\BookPC\My Documents\EST ltd USA\TRI
data\TRI_data.mdb;Trusted_Connection=yes;database=TRI_data")
'mySqlDataAdapter = New SqlDataAdapter("Select * from EST_TRI_Target_Data",
myConnection2)
Dim myDataSet As DataSet = New DataSet()
Dim myDataRow As DataRow
' Create command builder. This line automatically generates the update
commands for you, so you don't
' have to provide or create your own.
Dim myDataRowsCommandBuilder As OleDbCommandBuilder = New
OleDbCommandBuilder(dsCmd2)
' Set the MissingSchemaAction property to AddWithKey because Fill will not
cause primary
' key & unique key information to be retrieved unless AddWithKey is
specified.
dsCmd2.MissingSchemaAction = MissingSchemaAction.AddWithKey
dsCmd2.Fill(myDataSet, "EST_TRI_Target_Data")
myDataRow = myDataSet.Tables("EST_TRI_Target_Data").NewRow()
'myDataRow("TRI_Facility_ID") = "gs5436t3tsata"
'myDataRow("Parent_Company_Duns") = "db Enterprises"
'myDataRow("County") = "Nassau"
myDataSet.Tables("EST_TRI_Target_Data").Rows.Add(myDataRow)
myDataSet.Tables("EST_TRI_Target_Data").Rows(0)("ID") =
dsCmd2.MissingSchemaAction
Do While i < 21
i = i + 1
'SearchText = IIf(TextBox2.Text = "", "Tech Contact Name" & "</td><td><font
color=#990000>", TextBox2.Text)
SearchText = IIf(TextBox2.Text = "", DataFields(i, 0) & "</td><td><font
color=#990000>", TextBox2.Text)
gOptions = "rtfWholeWord"
'RichTextBox1.Find (FindString, StartPos, EndPos, Options)
' options: rtfNoHighlight,rtfWholeWord, rtfMatchCase
TextLength = RichTextBox1.TextLength
PosOne = RichTextBox1.Find(SearchText, 0, RichTextBoxFinds.NoHighlight)
PosTwo = RichTextBox1.Find("</font>", PosOne, RichTextBoxFinds.NoHighlight)
RichTextBox1.SelectionStart() = (PosOne + 29 + DataFields(i, 1))
FieldSize = PosTwo - (PosOne + 29 + DataFields(i, 1))
RichTextBox1.SelectionLength = FieldSize
'StoremyData.DesignMode.Tables(0).Rows(i)(DataFields(i, 0)) =
RichTextBox1.SelectedText
'MsgBox(RichTextBox1.SelectedText)
myDataSet.Tables("EST_TRI_Target_Data").Rows(0)(DataFields(i, 0)) =
RichTextBox1.SelectedText
'myDataRow(DataFields(i, 0)) = RichTextBox1.SelectedText
' If PosOne = -1 Then
' MsgBox("Text not found")
' Else
' MsgBox("Text Found")
' End If
Loop
'***************************************************************************
'myDataSet.Tables("EST_TRI_Target_Data").Rows.Add(myDataRow)
Debug.WriteLine(myDataRowsCommandBuilder.GetInsertCommand.CommandText)
dsCmd2.Update(myDataSet, "EST_TRI_Target_Data")
myConnection2.Close() Tag: LDAP: User associate to computer Tag: 140523
How to insert data row and reading out the ID of the new dataset
Hello there,
what is the best way to add an dataset and, then, to read out the ID
value of the created dataset?
ExecuteNonQuery() does not retrieve informations about the new ID of
the dataset. Of course I can execute a statement like this: SELECT
MAX(ID) from TableName, but this would not work, if the ID is of type
string (this could be if someone likes to create a GUID string as ID
value).
Is there a possibility to work with a Dataset by setting the
SelectCommand and UpdateCommand properties? How to I define the
SelectCommand to fetch the ID of the new dataset?
Regards,
Norbert Tag: LDAP: User associate to computer Tag: 140522
System.Transactions.Diagnostics.DiagnosticTrace throws an exception of initialization
I use .Net 2.0 and connect to a database access, on the
connection.open() I've this message "The type initializer for
'System.Transactions.Diagnotics.DiagnosticTrace' threw an exception"
Code :
public DataSet GetData(string SqlQuery)
{
using (OleDbConnection connection = new
OleDbConnection(m_ConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand(SqlQuery,
connection);
command.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new
OleDbDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
connection.Close();
return ds;
}
}
Thanks for your help Tag: LDAP: User associate to computer Tag: 140521
Sharing a DataSet among different Projects in a solution?
I have genearated a Typed DataSet in a C# project and am able to use it in
the from designer (I can drop a dataset Object from tool box and Set its
DataSetName Property this typed dataset very normally)
my Question is:
Can I share this typed dataset with other projects in solution so I can use
in their form designer?
the reason I need this is
I guess regerating a Type in another project (Assembly) actually makes a new
type that is not considered the same by the .Net Runtime(even if the
definition is exactly the same) Tag: LDAP: User associate to computer Tag: 140513
From ADO.NET 1.1 to SQL 2005 and SQL 2008
Dear Sirs.
I have Client Server Application
on Client Side i have .NET 1.1 WinForm Application
on Server Side i have SQL Server 2000
I'm using "OLE DB PROVIDER FOR SQL SERVER" for the Data Access
1)
I'd like to upgrade Server Side to SQL Server 2005 (I will copy same
database with users to sql2005)
Should i update Clients to .NET 2.0 too ?
Do i need install Native Client Lib on Client ?
2)
when SQL Server 2008 is Relesed
Can i connect to it from .NET 1.1 Application ?
Thank you in Advance. Tag: LDAP: User associate to computer Tag: 140512
finding column/row that causes System.Number.FormatException
I'm reading in xml into a dataset. I'm having to mess around with the
types of the xsd as well, since there are many null values in the
data. The data is about 25% string, 10% int, the rest decimals.
When I read this data in I frequently get a
System.Number.FormatException. No surprise, since I'm messing with
types in the xsd. But there is no indication of what row, column or
string caused the error. So I'm doing this by process of elimination.
Which is taking forever, due to the presence of nulls. I have no
ability to modify the data really.
Is there *any* way to set a breakpoint on
System.Number.ConvertToNumber()? That might not be the exact method
call... The exception has no data, the innerexception is null and the
msg tells me basically nothing. Grr.
Also, there are several thousand rows in about 85 tables. Tag: LDAP: User associate to computer Tag: 140510
Strongly Typed DataSets and "Refresh the data table" Option
Hi,
Using Visual Studio 2005 and SQL Server 2005:
I am trying to understand the stored procedures that Strongly Typed Datasets
wizard generates for me.
When we create a new strongly typed Datasets, and choose the following path:
Choose connection-> Create new stored procedures -> Enter SQL (select * from
tbl) -> Advanced Options -> Refresh the data table
We have an advanced option to refresh the data table. When we check the
option, the wizard adds a select statement to the end of SP_INSERT and
SP_UPDATE.
I don't understand how the result of the added select statement (to the
insert and update stored procedures) are being read back by the internal
DataAdapter. What makes the table adapter reads the result of the select
statement after insert or update operations?
A link to an online article would greatly help.
Thank you,
Max Tag: LDAP: User associate to computer Tag: 140509
Hi,
How to search the user (or users) associate to computer by ldap.