Monday, March 12, 2012

how to correctly build a formview dynamically/programmatically/code behind (did i do this

What i've written worksCool(it does what it's being asked to do) but i was wondering if this is the correct way to programmatically bind and alter the formview
Reason: We have various needs that will need to be achieved like, various SQL statements, variables & rules... so i was needing more control over what the wizard provides...

So i was wondering if this way is the "Best practice" and etc..

**Also i gotta figure out how to keep it form inserting a row on "refresh button" & I couldn't get itemUpdated to work?Confused

For brevity of code I'll post the ItemTemplate, which is replaced by EditItemTemplate or InsertItemTemplate with <%#Bind()%> on the Textboxes if necessary.

<asp:LabelID="lblError"runat="server"></asp:Label><br/>

<br/>

<asp:FormViewID="FormView1"runat="server"OnModeChanging="FormView1_ModeChanging"OnItemUpdating="FormView1_ItemUpdating"DataKeyNames="RowID"OnItemInserting="FormView1_ItemInserting">

<ItemTemplate>
<tablestyle="width: 338px; height: 264px">

<tr>
<tdstyle="width: 100px">Employee Id :</td>|
<tdstyle="width: 100px"><asp:LabelID="Label1"runat="server"Text='<%# Eval("RowID") %>'></asp:Label></td>
</tr>

<tr>
<tdstyle="width: 100px">First Name:</td>
<tdstyle="width: 100px"><asp:LabelID="Label2"runat="server"Text='<%# Eval("FirstName") %>'></asp:Label></td>
</tr>

<tr>
<tdstyle="width: 100px">Last Name:</td>
<tdstyle="width: 100px"><asp:LabelID="Label6"runat="server"Text='<%# Eval("LastName") %>'></asp:Label></td>
</tr>

<tr>
<tdstyle="width: 100px">Title:</td>
<tdstyle="width: 100px"><asp:LabelID="Label3"runat="server"Text='<%# Eval("Title") %>'></asp:Label></td>
</tr>

<tr>
<tdstyle="width: 100px">Phone #:</td>
<tdstyle="width: 100px"><asp:LabelID="Label4"runat="server"Text='<%# Eval("PhoneNumber") %>'></asp:Label></td>
</tr>

<tr>
<tdstyle="width: 100px">Notes</td>
<tdstyle="width: 100px"><asp:LabelID="Label5"runat="server"Height="85px"Text='<%# Eval("Notes") %>'Width="216px"></asp:Label></td>
</tr>

</table>

//These values change based on the template (Update CommandName="Update" ) or (Insert CommandName="Insert")
<asp:LinkButtonID="editButton"runat="server"CommandName="Edit">Edit</asp:LinkButton>|<asp:LinkButtonID="createButton"runat="server"CommandName="New">Create New</asp:LinkButton><br/>

<br/>

</ItemTemplate>

Code behind:

1public partialclass _Default : System.Web.UI.Page2{3//global variables45int myRowID;678protected void Page_Load(object sender, EventArgs e)9 {10//COMING IN FRESH START AT 1 ELSE USE WHATEVER VALUE myRowID is passed1112if (myRowID ==0)13 {14 myRowID = 1001;15 }1617if (!Page.IsPostBack)18 {19 BindData();20 }2122 }2324//BIND DATA25protected void BindData()26 {27//Create Connection28string strConnectionString = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;29 SqlConnection myConnection =new SqlConnection(strConnectionString);3031//Create the Command32string strCommandText ="SELECT * FROM [Fishbowl] WHERE ([RowID] = '"+myRowID+"')";33 SqlCommand myCommand =new SqlCommand(strCommandText, myConnection);3435//open the connection36 myConnection.Open();3738 FormView1.DataSource = myCommand.ExecuteReader();39 FormView1.DataBind();4041//Close Connection42 myConnection.Close();4344 }454647CREATE A NEW KEY/ROWID48public int getLastID()49 {50//Create Connection51string strConnectionString = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;52 SqlConnection myConnection =new SqlConnection(strConnectionString);5354//Create the Command55string strCommandText ="SELECT max(RowID) FROM [Fishbowl] ";56 SqlCommand myCommand =new SqlCommand(strCommandText, myConnection);5758//open the database connection59 myConnection.Open();6061//convert the value into something we can use62int lastID = (int)myCommand.ExecuteScalar()+1;6364//close the connection65 myConnection.Close();66return lastID;67 }686970//SWITCH THE FORMVIEW MODES71protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e)72 {73switch (e.NewMode)74 {75case FormViewMode.Edit:76 FormView1.ChangeMode(FormViewMode.Edit);77break;78case FormViewMode.Insert:79 FormView1.ChangeMode(FormViewMode.Insert);80break;81default:82 FormView1.ChangeMode(FormViewMode.ReadOnly);83break;84 }85 BindData();86 }8788//UPDATE THE CONTENT89protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)90 {91//Create Connection92string strConnectionString = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;93 SqlConnection myConnection =new SqlConnection(strConnectionString);9495try96 {97//Query to execute98string strQuery ="UPDATE [Fishbowl] SET [FirstName] = @dotnet.itags.org.FirstName, [LastName] = @dotnet.itags.org.LastName, [Title] = @dotnet.itags.org.Title, [PhoneNumber] = @dotnet.itags.org.PhoneNumber, [Notes] = @dotnet.itags.org.Notes WHERE [RowID] = @dotnet.itags.org.RowID";99100//Create the Command101 SqlCommand myCommand =new SqlCommand(strQuery, myConnection);102103// FormViewRow row = FormView1.Row;104 //Set up parameters105 TextBox txtFirstName = (TextBox)FormView1.FindControl("txtFirstName");106 TextBox txtLastName = (TextBox)FormView1.FindControl("txtLastName");107 TextBox txtTitle = (TextBox)FormView1.FindControl("txtTitle");108 TextBox txtPhoneNumber = (TextBox)FormView1.FindControl("txtPhoneNumber");109 TextBox txtNotes = (TextBox)FormView1.FindControl("txtNotes");110111 myCommand.Parameters.AddWithValue("@dotnet.itags.org.FirstName", txtFirstName.Text );112 myCommand.Parameters.AddWithValue("@dotnet.itags.org.LastName", txtLastName.Text);113 myCommand.Parameters.AddWithValue("@dotnet.itags.org.Title", txtTitle.Text);114 myCommand.Parameters.AddWithValue("@dotnet.itags.org.PhoneNumber", txtPhoneNumber.Text);115 myCommand.Parameters.AddWithValue("@dotnet.itags.org.Notes", txtNotes.Text);116 myCommand.Parameters.AddWithValue("@dotnet.itags.org.RowID", myRowID);117118//open the database connection119 myConnection.Open();120 myCommand.ExecuteNonQuery();121122 }123catch (Exception ex)124 {125//Houston We have problems126127 lblError.Text = ex.Message;128 }129finally130 {131//close the database connection132 myConnection.Close();133 }134135 FormView1.ChangeMode(FormViewMode.ReadOnly);136 BindData();137 }138139//i guess if we can get this work, then we can validate the updated row140141void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)142 {143// for some strange reason this won't fire.. really don't know why144 }145146//Insert ROW147148149protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)150 {151152//Create Connection153string strConnectionString = ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString;154 SqlConnection myConnection =new SqlConnection(strConnectionString);155156try157 {158//Query to execute159string strQuery ="INSERT [Fishbowl] ([FirstName], [LastName], [Title], [PhoneNumber] , [Notes], [RowID]) VALUES ( @dotnet.itags.org.FirstName, @dotnet.itags.org.LastName,@dotnet.itags.org.Title, @dotnet.itags.org.PhoneNumber, @dotnet.itags.org.Notes, @dotnet.itags.org.RowID)";160161//Create the Command162 SqlCommand myCommand =new SqlCommand(strQuery, myConnection);163164//Set up parameters165 TextBox txtFirstName = (TextBox)FormView1.FindControl("txtFirstName");166 TextBox txtLastName = (TextBox)FormView1.FindControl("txtLastName");167 TextBox txtTitle = (TextBox)FormView1.FindControl("txtTitle");168 TextBox txtPhoneNumber = (TextBox)FormView1.FindControl("txtPhoneNumber");169 TextBox txtNotes = (TextBox)FormView1.FindControl("txtNotes");170171 myCommand.Parameters.AddWithValue("@dotnet.itags.org.FirstName", txtFirstName.Text);172 myCommand.Parameters.AddWithValue("@dotnet.itags.org.LastName", txtLastName.Text);173 myCommand.Parameters.AddWithValue("@dotnet.itags.org.Title", txtTitle.Text);174 myCommand.Parameters.AddWithValue("@dotnet.itags.org.PhoneNumber", txtPhoneNumber.Text);175 myCommand.Parameters.AddWithValue("@dotnet.itags.org.Notes", txtNotes.Text);176 myCommand.Parameters.AddWithValue("@dotnet.itags.org.RowID", getLastID());177178//open the database connection179 myConnection.Open();180 myCommand.ExecuteNonQuery();181182 }183catch (Exception ex)184 {185//Houston We have problems186 lblError.Text = ex.Message;187 }188finally189 {190//close the database connection191 myConnection.Close();192 }193194 FormView1.ChangeMode(FormViewMode.ReadOnly);195 myRowID = getLastID() - 1;196 BindData();197 lblError.Text ="Row Added";198 }199}200201

any help suggestions will be greatly appriecated thx in adv

well maybe this is a way to do it... so I'll go with this way until something breaks


another way is just to hi-jack the sqlDataSource Commands in the code behind..

if (condition 1) {

SqlDataSource1.SelectCommand ="SELECT * FROM [Fishbowl] WHERE ([RowID] = '"+myRowID+"')";

}else{

//condition2

SqlDataSource1.SelectCommand ="SELECT * FROM [Fishbowl] WHERE ([RowID] = '"+myRowID+"')";

}

Duh!!!!

This way i'll total control over what i want to query :)

Labels: , , , , , , , , , ,

How to correct 'error - input string not in correct format'

Can anyone help me correct this.

This line is giving an error

Code Snippet

dblAmount[2] = double .Parse (BD.dbCommands.ExecuteScalar("SELECT SUM([AR-PAYMENT AMOUNT]) " + strSql, BD.MyGlobal._ARConnection).ToString());

error = Input string not in correct format.

Code Snippet

public static object ExecuteScalar(string queryStr, OleDbConnection connStr)

{

if (connStr.State != ConnectionState.Open)

{

connStr.Open();

}

OleDbCommand comm = new OleDbCommand(queryStr, connStr);

object returnObject;

returnObject = comm.ExecuteScalar();

return returnObject;

}

You are attempting to convert the result of executing ExecuteScalar to a double. If the result is not in a format supported by double then you'll get an error. Try storing the results in a string first to verify the results are what you expected. If no resultset is returned then you'll get a null which will fail.

In general you should avoid combining so much code into one line. It doesn't help performance at all, makes debugging harder and is harder to read. Separate out function calls to make it easier for you.

Michael Taylor - 5/30/07

http://p3net.mvps.org


Thanks for the help - could you explain this further for me

"In general you should avoid combining so much code into one line. It doesn't help performance at all, makes debugging harder and is harder to read. Separate out function calls to make it easier for you."


There really isn't a lot to explain. Where does the problem lie in your code? You aren't sure because the following line is doing several different things.

Code Snippet

dblAmount[2] = double .Parse (BD.dbCommands.ExecuteScalar("SELECT SUM([AR-PAYMENT AMOUNT]) " + strSql, BD.MyGlobal._ARConnection).ToString());

It could lie in the call to Parse, ExecuteScalar, perhaps the strSql or _ARConnection variables or even the assignment to the array. Many different places where things can go wrong. Additionally a cursory glance makes it difficult to tell what exactly is being passed to Parse as a parameter. There are several sets of parenthesis.

You are having a hard time figuring out what is going wrong because this is one busy line. By breaking it up you can more easily figure out where the problem lies. Even better is the fact that you can single step through the debugger and confirm each line executes the way you want. By using the debugger you'll be able to quickly identify whether the result of ExecuteScalar is bad, the result from Parse is bad, whatever. Now imagine that you come back to this code 6 months later. Or worse yet someone else has to manage this code. It is a lot of extra work.

Many "old" C programmers would write code like this believing that the less source lines you have the smaller and faster the code would run. This simply is not true. The compiler will generate fast and optimal code whether you put code on one line or several lines. Therefore you should strive for readability of code over writing the smallest number of lines. There are places where it makes sense to consolidate lines but not here. Here is how I'd write the code if I were doing it:

Code Snippet

object result = BD.dbCommands.ExecuteScalar("SELECT SUM([AR-PAYMENT AMOUNT]) " + strSql, BD.MyGlobal._ARConnection);

string strResult = (result != null) ? result.ToString() : "0";

dblAmount[2] = double.Parse(strResult);

Now the above code is probably broken out more than I would normally do. I generally recommend that function calls reside on a line by themselves. Use variables to store the results. You can consolidate a method call to a variable (like .ToString()) in an assignment for simplicity. The important point is "where would I need to step through if something goes wrong". Functions are at the top of the list so break lines that way. Of course over time you'll find your own technique that works well for you but the above may help to get you started.

Michael Taylor - 5/30/07

http://p3net.mvps.org


Thanks very much for your advice, I am an 'old' VB programmer who is just getting into c# so everything helps.


I would also suggest preferring TryParse instead of Parse.

Labels: , , , , , , , , , , , ,

how to Copy/Clone a derived DataTable

I would like to add a few properties and methods to an ADO.NET DataTable. So
the normal thing would be to derive a class:
Public Class MyTable
Inherits DataTable
Private This As That
Private TheOtherThing As Whatever
Now, a DataTable has Clone and Copy methods. Is there a straight forward way
for my Derived class to implement Clone and Copy, and rely on the base class
to copy the schema and data? Or do I have to do the heavy lifting myself?
I mean, I can create Clone and Copy functions in the derived MyTable class,
mark them as Shadows to have them replace or override these functions in the
base class, but is there any easy way to copy the schema and data?
ThanksIf it's 2.0, then Serialize and Deserialize your derived DataTable.
- Sahil Malik [MVP]
ADO.NET 2.0 book -
http://codebetter.com/blogs/sahil.malik/archive/2005/05/13/63199.aspx
----
"Mark" <mark.bax@.blaisesoft-xxx.com> wrote in message
news:%235wOqEfSGHA.1204@.TK2MSFTNGP12.phx.gbl...
>I would like to add a few properties and methods to an ADO.NET DataTable.
>So the normal thing would be to derive a class:
> Public Class MyTable
> Inherits DataTable
> Private This As That
> Private TheOtherThing As Whatever
> Now, a DataTable has Clone and Copy methods. Is there a straight forward
> way for my Derived class to implement Clone and Copy, and rely on the base
> class to copy the schema and data? Or do I have to do the heavy lifting
> myself?
> I mean, I can create Clone and Copy functions in the derived MyTable
> class, mark them as Shadows to have them replace or override these
> functions in the base class, but is there any easy way to copy the schema
> and data?
> Thanks
>

Labels: , , , , , , , , , , ,

How to copy the content of a textbox with a button click?

Hi, i use Visual Web Developer 2005 express with Visual Basic and asp.net. I have a formView with a textbox and a button, i want to be able to copy the content of the textbox clicking on the button to paste the content in somewhere else.

Any one can help me with the code?

<asp:FormView ID="FormView1" runat="server" CellPadding="4" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="Both">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<ItemTemplate>
<table style="width: 561px; height: 85px" border="1" bordercolor="gainsboro">
<tr>
<td style="width: 156px; text-align: left;">
<asp:Label ID="Label3" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Small"
Text="Test:"></asp:Label></td>
<td style="width: 302px">
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ed_order_number", "{0}") %>'
Width="250px"></asp:TextBox></td>
<td style="width: 54px; text-align: center;">
<asp:Button ID="Button1" runat="server" Text="Copy" OnClick="Button1_Click" /></td>
</tr>

</table>
</ItemTemplate>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderTemplate>
<table style="width: 401px; height: 67px">
<tr>
<td colspan="3" rowspan="3" style="height: 34px">
<asp:Label ID="Label37" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="Medium"
Text="Order Details"></asp:Label></td>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</HeaderTemplate>
</asp:FormView>

Are you looking for something like this?

protected void Button1_Click(object sender, EventArgs e){TextBox TextBox1 = FormView1.FindControl("TextBox1")as TextBox;if (TextBox1 ==null) {return; }string value = TextBox1.Text;// Do what you want with value here}

I need to simulate the Ctrl + C function on the button to copy the content of the textbox, and after paste it in somewhere else.


bonfa:

Hi, i use Visual Web Developer 2005 express with Visual Basic and asp.net. I have a formView with a textbox and a button, i want to be able to copy the content of the textbox clicking on the button to paste the content in somewhere else.

Any one can help me with the code?

Hi there,

Have a look at this forum with a working examplehttp://forums.asp.net/t/1047507.aspx


I use Visual basic not C Sharp.


The code is all Javascript thoughWink

Labels: , , , , , , , , , , , ,

How to copy single row in datagrid

Hi to all,

I would like to copy data (whole single row at once) from web-based datagrid to off line Excel spreadsheet. I am using Vb.net and Access database.

Please help me!

Regards

Harsh

Here is an example that uses the Northwind database as an example. It creates a CSV file that Excel can open directly, so there is no need to start interfacing with the COM Excel DLL. If your text contains commas, you can use another seperator such as vbTab. Hope this helps

<%@.PageLanguage="VB" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<scriptrunat="server">

ProtectedSub Gridview1_RowCommand(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.GridViewCommandEventArgs)

If e.CommandName ="Export"Then

' Create an instance of StreamWriter to write text to a file.

Using swAs System.IO.StreamWriter =New System.IO.StreamWriter(MapPath("App_Data/TestFile.csv"))

Dim rAs GridViewRow = Gridview1.Rows(CInt(e.CommandArgument))

Dim csvLineAsString =String.Empty

For indexAsInteger = 0To r.Cells.Count - 1

If csvLine =""Then

csvLine = r.Cells(index).Text

Else

csvLine +="," + r.Cells(index).Text

EndIf

Next

sw.WriteLine(csvLine)

sw.Close()

EndUsing

EndIf

EndSub

</script>

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<asp:GridViewID="Gridview1"runat="server"AutoGenerateColumns="False"DataKeyNames="CustomerID"

DataSourceID="SqlDataSource1"OnRowCommand="Gridview1_RowCommand">

<Columns>

<asp:TemplateFieldHeaderText="Click link to Export">

<ItemTemplate>

<asp:LinkButtonID="LinkButton1"runat="server"CommandName="Export"CommandArgument='<%# Container.DataItemIndex %>'>Export</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundFieldDataField="CustomerID"HeaderText="CustomerID"ReadOnly="True"SortExpression="CustomerID"/>

<asp:BoundFieldDataField="CompanyName"HeaderText="CompanyName"SortExpression="CompanyName"/>

<asp:BoundFieldDataField="PostalCode"HeaderText="PostalCode"SortExpression="PostalCode"/>

<asp:BoundFieldDataField="Phone"HeaderText="Phone"SortExpression="Phone"/>

</Columns>

</asp:GridView>

<asp:SqlDataSourceID="SqlDataSource1"runat="server"ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"

SelectCommand="SELECT [CustomerID], [CompanyName], [PostalCode], [Phone] FROM [Customers]">

</asp:SqlDataSource>

</form>

</body>

</html>


Thanks sbyard for the code. I appreciate you. I will try this code and hope it will help me.

Regards

Harsh

Labels: , , , , , , , , , ,

How to copy one datatable to another

Hi

I've got a typed Dataset class, myDatasetclass, which I generate an instance of (myDataset is the instance) and then store data locally inside the tables of this dataset instance.

Instead of "Filling" say, myDataset.tblUsers with a dataadapter directly however, my app sends this table to a windows service, which contacts a backend database, gets the data, and returns the 'myDataset.tblUsers', containing data, to my app.

Problem is, I need to be able to say something like:

Code Snippet

myDatasetclass myDataset = new myDatasetclass();

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

(this last part 'myDataset.tblUsers' is the table being sent to the service)

But it says myDataset.tblUsers (the first part above before the '=', is read-only, and can't be passed the new table with data which was returned from myService.

However, if I do this it works fine:

Code Snippet

Datasetclass.tblUsers mytblUsers = new Datasetclasss.tblUsers();

mytblUsers = myService.GetDatafromdbase(mytblUsers);

Only then, I'm filling a table by itself, instead of a table within the Dataset with all the relationships already established (because it's part of a class which establishes these relationships.)

It is becuase that DataTable can't be serialized and send as a result of WebService. Use Dataset for that, and you will get the table from dataset like this:

tblUsers = myService.GetDatafromdbase().Tables[0]; //if GetDatafromdbase returns a dataset that contain datatable tblUsers.

One more thing is that when you returning data, for this case table, better is to call it asynchronously, because every method has asinchronous method and event when that request is completed, it will be like this:

myService.GetDatafromdbaseCompleted += new GetDatafromdbaseCompletedEventHandler(OnUsersData);
myService.GetDatafromdbaseAsync();

for this you will create handler named OnUsersData:

private void OnUsersData(object sender, GetDatafromdbaseCompletedEventArgs e)
{
if (e.Result != null)
{
tblUsers = e.Result.Tables[0];
//do some other stuff if necessary, fill some grid, raise some other event, or any other action.
}
}


Thanks

Where you have:

Code Snippet

tblUsers = myService.GetDatafromdbase().Tables[0]

Do you mean:

Code Snippet

myDataset.tblUsers = myService.GetDatafromdbase().Tables[0]

Because tblUsers is partof the myDataset Dataset, and having this and = returns a 'read-only' error.


The myDataSet.tblUsers property is ReadOnly and can't be assigned to a new DataTable.

Instead you could try Merge:

myDataset.tblUsers.Merge(myService.GetDatafromdbase().Tables[0])

this will bring in all rows from the datatable.


How come I can still 'Fill' the table using an adapter if it is read-only?

eg:

adap.fill(myDataset.tblUsers);


What I did is auto-generated a typed dataset from my database, which also created a C# class file with all the tables and properties and relationships, whcih I intended to just create an instance of and write data to, but instead of using Fill, I'd use the

Code Snippet

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

Where the section in brackets is the table being sent to the service empty to be returned containing data.

Would it be best then to just 'rebuilt' all of this dataset in code (thats a lot of code for 50+ tables and relationships), and redefine all the relationships in code, seeing as I can't make an instance of the class mentioned above to write to?

Eg:

Code Snippet

myDataset newdataset = new myDataset();

myDataset.tblUsers newtblUsers = new myDataset.tblUsers();

myDataset.tblUsers newtblUsers = new myDataset.tblUsers();

...etc...

then put the tables in the dataset and define all the relationships?

Seems strange I can't just create an instance of my entire dataset class and then write table data into it with:

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

when using an adapter I could fill the myDataset.tblUsers table with data regardless of it being read-only.

If i create an instance of the table, but not the table within the dataset, the above works too, but then its a table by itself without relationships.

Labels: , , , , , , , , , , , , ,

How to copy new data from server to a local database.

Can somebody tell me what is the easiest way to copy new data from MySQL database placed on server to a local Access 2003 DB on my computer? (Using Visual Basic 2005 PRO)

I want to copy whole rows (about 25 columns: strings, doubles, booleans and one BLOB).

Thanks

you need two connections that return two datatables once you have your datatables you can do something like this If the table schemas are the same :

MyAccessDT.Merge(MySQLDT)

Labels: , , , , , , , , , , ,

How to copy n paste .asp files to Solution Explorer and have it show up there?

Hi,
I have just installed Visual Studio.net 2003 Enterprise Architect.
I have been using Visual Interdev so far, and I am used to be able to select
from a desktop, drag bunch of .asp files, and drop them into a Project
Explorer window and have it show there as a tree of files. Is there some
setting that I need to enable in Visual Studio.Net to do the drag and drop
to Solution Explorer (which seems to be the equivalent of Project Explorer
in InterDev) and have it show there as a tree of files?
Thank you for your help.Drop into the folder in Windows Explore, show all files and then include in
project is one option.
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
*************************************************
Think outside the box!
*************************************************
"Jason Robertson" <jason6869@.msn.com> wrote in message
news:Y9udnQFGsI3wN-fcRVn-pA@.comcast.com...
> Hi,
> I have just installed Visual Studio.net 2003 Enterprise Architect.
> I have been using Visual Interdev so far, and I am used to be able to
> select
> from a desktop, drag bunch of .asp files, and drop them into a Project
> Explorer window and have it show there as a tree of files. Is there some
> setting that I need to enable in Visual Studio.Net to do the drag and drop
> to Solution Explorer (which seems to be the equivalent of Project Explorer
> in InterDev) and have it show there as a tree of files?
> Thank you for your help.
>

Labels: , , , , , , , , , , , , , ,

How to copy Modified Records In a DataSet to another Dataset??

I have created a dataset from database "DB1" table "T_DB1". I Loop throw the Dataset and make changes/modification tosome of the records. After that I try to update the Dataset.
Lets say the update fails because database is down. I would like to create a backup of the modified data in a different database so I can load it manually latter on in the real database.
I am currently going throw every row of the dataset and finding what has been modified and the inserting that record into the backup database.

... BUT Is there any better way of doing this?This forum is falling appart. Its not like it used to be.
There is a way to do this.

You simply have to dynamically change your SQL statement and connection.

Eg. If your using a SqlDataAdapter, just change the update command associated with it and set it's connection property to the new database. All rows that have been updated will call this function which will update your backup database... I would look something like this:

Try
'Update database (main database)

Catch ex as Exception

'Check exception, if database is down then...
newConnectionString = new sqlConnection(".....")
mySqlDataAdapter.UpdateCommand = new sqlcommand(newConnectionString)
UpdateCommand.commandtext = ".............."

'Update backup database

End Try


Thats right. Thanks

Labels: , , , , , , , , , , , , , ,

how to Copy Item one Gridview to another gridview

I have Two gridview left side where i populate data from Database and other will be empty at 1st time my requirement is when click any item and click to add button it will remove from that cell and add in to second gridview

same thing happens through drag and drop system Drag from one gridview to another well but it will be helpfull how to remove and add one gridview to another can someone give me idea

bye take care
regards
vikrant

Check out these links

http://forums.asp.net/p/1169459/1955946.aspx

http://www.codeproject.com/KB/HTML/SelectMoveRowsFromTables.aspx

Labels: , , , , , , , , , ,

How to copy gridview cell values?

I have a gridview that displays item #'s and my users want to be able to highlight any number and copy it by either right clicking or ctrl + c. But for some reason the individual cells can't be highlighted by double clicking. And when dragging over text it highlights the entire table!

<asp:GridView BorderWidth=1px BorderColor=Black Borderstyle=Solid HeaderStyle-BackColor=Aquamarine runat=server style="z-index: 100; left: 9px; position: absolute; top: 106px" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" ID="GridView1" AllowPaging="True" AllowSorting="True"> <Columns> <asp:BoundField DataField="itemNumber" HeaderText="#" SortExpression="itemNumber" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:BoundField DataField="FirstPayDate" HeaderText="First Pay Date" SortExpression="FirstPayDate" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:BoundField DataField="Screen" HeaderText="Screen" SortExpression="Screen" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:BoundField DataField="Problem" HeaderText="Problem" SortExpression="Problem" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:BoundField DataField="DateIn" HeaderText="Date in" SortExpression="DateIn" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" > <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col" ForeColor="#0000C0" /> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" /> </asp:BoundField> <asp:CommandField HeaderText="Action" SelectText="Fixed" ShowSelectButton="True"> <ItemStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CssClass="Col"/> <HeaderStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="2px" /> </asp:CommandField> </Columns> <PagerTemplate> Goto Page <asp:DropDownList ID="ddlPageSelector" OnSelectedIndexChanged="pageChange" runat="server" AutoPostBack="true"> </asp:DropDownList>  Total Errors: <asp:Label ID="lbl_Total" runat="server" Text="Label"></asp:Label> </PagerTemplate> <HeaderStyle BackColor="Aquamarine" /></asp:GridView>

Try using a TemplateField instead of the BoundField. Then use a span to display your info.

Labels: , , , , , , , , , , , ,

how to copy dataset?

Hi all,

I have 2 datasets, how to copy all tables and data from dataset1 to dataset2?

I m using:

Rows.Add(Rows[ n ].ItemArray);

but i found it's too slow..

is there any better solution? thanks

Hi there,

I believe that the Dataset class has a Copy() function which you can use. It returns a new Dataset and apparently it copies all the tables and data.

Here's a link to the relevant portion of MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatasetclasscopytopic.asp

No MSDN2 I'm afraid, it seems to be dying on me at the moment.

Hope that helps a bit, but sorry if it doesn't

Labels: , , , , , , , , ,

How to copy DataRows between DataTables?

Hi all,
I want to copy or move an existing DataRow wich belongs to a DataTable to
another DataTable, but I got the exception "This row already belongs to
another table".
I tried to use the ImportRow method, but this method inserts the row at the
end of the DataTable, and I need to put it at an specific position. The
method InsertAt returns the expeption ahead.
There's a way to copy a DataRow in a specific position? Or, maybe, a way to
detach the row from the original DataTable?
Thanks in advance,
Fabrício de Novaes Kucinskis.Well, I found a solution, copying the source row data to a new row, using
the ItemArray property, and then attaching the new row to the destination
table via InsertAt.
The problem now is that the row is attached to the end of the DataTable, not
in the position I set in InsertAt. My DataTable has a binded DataGrid.
I search the web, and it appears to be a .NET bug. Is it correct? If no,
what can I do? If yes, WHAT CAN I DO'?
Thanks again,
Fabrício.
"Fabrício de Novaes Kucinskis" <fabricio.nk@.uol.com.br> wrote in message
news:eF3NfRvPDHA.2480@.tk2msftngp13.phx.gbl...
> Hi all,
> I want to copy or move an existing DataRow wich belongs to a DataTable to
> another DataTable, but I got the exception "This row already belongs to
> another table".
> I tried to use the ImportRow method, but this method inserts the row at
the
> end of the DataTable, and I need to put it at an specific position. The
> method InsertAt returns the expeption ahead.
> There's a way to copy a DataRow in a specific position? Or, maybe, a way
to
> detach the row from the original DataTable?
> Thanks in advance,
>
> Fabrício de Novaes Kucinskis.
>
I am unsure if this is a bug or not. How you may get around this is use a sorted DataView on the DataTable and bind your grid to the DataView.
>--Original Message--
>Well, I found a solution, copying the source row data to a new row, using
>the ItemArray property, and then attaching the new row to the destination
>table via InsertAt.
>The problem now is that the row is attached to the end of the DataTable, not
>in the position I set in InsertAt. My DataTable has a binded DataGrid.
>I search the web, and it appears to be a .NET bug. Is it correct? If no,
>what can I do? If yes, WHAT CAN I DO'?
>Thanks again,
>
>Fabr=EDcio.
>
>"Fabr=EDcio de Novaes Kucinskis" <fabricio.nk@.uol.com.br> wrote in message
>news:eF3NfRvPDHA.2480@.tk2msftngp13.phx.gbl...
>> Hi all,
>> I want to copy or move an existing DataRow wich belongs to a DataTable to
>> another DataTable, but I got the exception "This row already belongs to
>> another table".
>> I tried to use the ImportRow method, but this method inserts the row at
>the
>> end of the DataTable, and I need to put it at an specific position. The
>> method InsertAt returns the expeption ahead.
>> There's a way to copy a DataRow in a specific position? Or, maybe, a way
>to
>> detach the row from the original DataTable?
>> Thanks in advance,
>>
>> Fabr=EDcio de Novaes Kucinskis.
>>
>
>.
>
Hi, David. Thanks for your answer.
I cannot use a DataView because the user wants to edit the data in DataGrid.
"David Brenchley" <brenchld@.iomega.com> wrote in message
news:052e01c33f50$e8771e00$a101280a@.phx.gbl...
I am unsure if this is a bug or not. How you may get
around this is use a sorted DataView on the DataTable and
bind your grid to the DataView.
>--Original Message--
>Well, I found a solution, copying the source row data to
a new row, using
>the ItemArray property, and then attaching the new row
to the destination
>table via InsertAt.
>The problem now is that the row is attached to the end
of the DataTable, not
>in the position I set in InsertAt. My DataTable has a
binded DataGrid.
>I search the web, and it appears to be a .NET bug. Is it
correct? If no,
>what can I do? If yes, WHAT CAN I DO'?
>Thanks again,
>
>Fabrício.
>
>"Fabrício de Novaes Kucinskis" <fabricio.nk@.uol.com.br>
wrote in message
>news:eF3NfRvPDHA.2480@.tk2msftngp13.phx.gbl...
>> Hi all,
>> I want to copy or move an existing DataRow wich
belongs to a DataTable to
>> another DataTable, but I got the exception "This row
already belongs to
>> another table".
>> I tried to use the ImportRow method, but this method
inserts the row at
>the
>> end of the DataTable, and I need to put it at an
specific position. The
>> method InsertAt returns the expeption ahead.
>> There's a way to copy a DataRow in a specific
position? Or, maybe, a way
>to
>> detach the row from the original DataTable?
>> Thanks in advance,
>>
>> Fabrício de Novaes Kucinskis.
>>
>
>.
>
>I cannot use a DataView because the user wants to edit the data in DataGrid.
And why do you think you can't edit your data anymore, if you use a
DataView' You still can!
Check it out - every DataTable has a "DefaultView" property, which
exposes the default view of the table - you can use that to set the
Sort property of the view, and then use the view as your grid's
source, instead of your table directly.
Read up on ADO.NET in a good book - it has *LOTS* of goodies to offer!
DataView also allow you to specify e.g. a RowFIlter - very powerful
stuff. And everything stays editable!
Marc
================================================================Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
Oh my God. I don't believe I lost a lot of time, based on this supposition.
Marc, thanks for your answer. I'll try your tips.
"Marc Scheuner [MVP ADSI]" <m.scheuner@.inova.SPAMBEGONE.ch> wrote in message
news:c5h7gvkjkoq9ap4m9t3pdr1h41gbr9bp0h@.4ax.com...
> >I cannot use a DataView because the user wants to edit the data in
DataGrid.
> And why do you think you can't edit your data anymore, if you use a
> DataView' You still can!
> Check it out - every DataTable has a "DefaultView" property, which
> exposes the default view of the table - you can use that to set the
> Sort property of the view, and then use the view as your grid's
> source, instead of your table directly.
> Read up on ADO.NET in a good book - it has *LOTS* of goodies to offer!
> DataView also allow you to specify e.g. a RowFIlter - very powerful
> stuff. And everything stays editable!
> Marc
> ================================================================> Marc Scheuner May The Source Be With You!
> Bern, Switzerland m.scheuner(at)inova.ch

Labels: , , , , , , , , , , ,

how to copy data from excel to oracle forms

hi all
i want to copy the data of excel sheet into my oracle form
regardsExcel -> CSV -> Oracle
Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).
Transfer the .csv file to the Oracle server.
Create the Oracle table, using the SQL CREATE TABLE statement to define the table's column lengths and types. Here's an example of an sqlplus 'CREATE TABLE' statement:
CREATE TABLE SPECIES_RATINGS
(SPECIES VARCHAR2(10),
COUNT NUMBER,
RATING VARCHARC2(1));
Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:
load data
infile spec_rat.csv
replace
into table species_ratings
fields terminated by ','
(species,count,rating)
Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:
% sqlload userid=username/password control=<filename.ctl> log=<filename>.log
This will create a log file <filename>.log. Check it for loading errors.
Use these sqlplus commands to check the Oracle table:
DESCRIBE SPECIES_RATINGS;
SELECT COUNT(*) FROM SPECIES_RATINGS;
SELECT * FROM SPECIES_RATINGS WHERE ROWNUM < 6;
You're done Hakuna mattata.
Excel -> CSV -> Oracle
Save the Excel spreadsheet as file type 'CSV' (Comma-Separated Values).
Transfer the .csv file to the Oracle server.
Create the Oracle table, using the SQL CREATE TABLE statement to define the table's column lengths and types. Here's an example of an sqlplus 'CREATE TABLE' statement:
CREATE TABLE SPECIES_RATINGS
(SPECIES VARCHAR2(10),
COUNT NUMBER,
RATING VARCHARC2(1));
Use sqlload to load the .csv file into the Oracle table. Create a sqlload control file like this:
load data
infile spec_rat.csv
replace
into table species_ratings
fields terminated by ','
(species,count,rating)
Invoke sqlload to read the .csv file into the new table, creating one row in the table for each line in the .csv file. This is done as a Unix command:
% sqlload userid=username/password control=<filename.ctl> log=<filename>.log
This will create a log file <filename>.log. Check it for loading errors.
Use these sqlplus commands to check the Oracle table:
DESCRIBE SPECIES_RATINGS;
SELECT COUNT(*) FROM SPECIES_RATINGS;
SELECT * FROM SPECIES_RATINGS WHERE ROWNUM < 6;
You're done Hakuna mattata.
Try this and reply soon
hi
I am using Windows XP operating system. I want to copy data from excel to oracle. Is there any way...
with regards,
chaithanya
you can try this utility from sourceforge
http://sourceforge.net/projects/quickload
If the oracle is on unix server and the excell file is on my desktop which runs on windows, where will the location of parfile, logs be and how will i specify the path for excel file on unix from my windows.
hakuna Matata rafiki
hello
you can use ODBC to configure an Excel sheet as if it is an Oracle table using Database link. Then you just create a view or run a normal SQL query to show the data on your form
It is tested and working
to know how to go about doing the configuration of this technique, i have on my website a step by step help
http://www.e-ammar.com/Oracle_TIPS/HS/configuring_generic_database_con.htm
regardsa
Ammar Sajdi
www.e-ammar.com
oracle consultant
PROCEDURE get_from_xls IS
CONVID PLS_INTEGER;
APPID PLS_INTEGER;
i number;
x number;
v_name VARCHAR2(100);
v_BRN varchar2(10);
v_NO varchar2(10);
OUT_FILR TEXT_IO.FILE_TYPE;
BEGIN
synchronize;
-- Appid := dde.app_begin('C:\Program Files\Microsoft Office\Office\excel.exe C:\ora_xls\creadit.xls',dde.app_mode_minimized);
Appid := dde.app_begin('E:\Program Files\Microsoft Office\Office11\excel.exe C:\oracle_excel\EMP_ALL.xls',dde.app_mode_minimized);
dde.app_focus(appid);
convid := dde.initiate('EXCEL',/*:BLOCK2.SHEET_NAME*/'Sheet1' );
x := 0;
FOR I IN 2..100000 loop
dde.request(convid,'R' || to_char(i) ||'C1',v_brn,dde.cf_text,100000);
dde.request(convid,'R' || to_char(i) ||'C2',v_no,dde.cf_text,100000);
dde.request(convid,'R' || to_char(i) ||'C3',v_name,dde.cf_text,100000);
if substr(v_no,1,length(v_no)-2) is null then exit;
end if;
insert into EXCEL_TBL(
CODE ,
NAME )
VALUES(
substr(v_brn,1,length(v_brn)-2),
substr(v_no,1,length(v_no)-2));
x:= x + 1;
end loop;
COMMIT;
dde.terminate(convid);
dde.app_end(appid);
END;
--
Message was edited by:
user575536
hai chaithanya,
am using Windows XP operating system. I want to copy data from excel to oracle. Is there any way...
regard's
polaiah
please!
what is dde?
(dde.app_focus(appid), dde.initiate,dde.request,....)
thanks!
____________________________________
>PROCEDURE get_from_xls IS
>CONVID PLS_INTEGER;
>APPID PLS_INTEGER;
>i number;
>x number;
>v_name VARCHAR2(100);
>v_BRN varchar2(10);
>v_NO varchar2(10);
>OUT_FILR TEXT_IO.FILE_TYPE;
>BEGIN
>synchronize;
>-- Appid := dde.app_begin('C:\Program Files\Microsoft Office\Office\excel.exe >C:\ora_xls\creadit.xls',dde.app_mode_minimized);
>Appid := dde.app_begin('E:\Program Files\Microsoft Office\Office11\excel.exe >C:\oracle_excel\EMP_ALL.xls',dde.app_mode_minimized);
>dde.app_focus(appid);
>convid := dde.initiate('EXCEL',/*:BLOCK2.SHEET_NAME*/'Sheet1' );
>x := 0;
>FOR I IN 2..100000 loop
>dde.request(convid,'R' || to_char(i) ||'C1',v_brn,dde.cf_text,100000);
>dde.request(convid,'R' || to_char(i) ||'C2',v_no,dde.cf_text,100000);
>dde.request(convid,'R' || to_char(i) ||'C3',v_name,dde.cf_text,100000);
>if substr(v_no,1,length(v_no)-2) is null then exit;
>end if;
>insert into EXCEL_TBL(
>CODE ,
>NAME )
>VALUES(
>substr(v_brn,1,length(v_brn)-2),
>substr(v_no,1,length(v_no)-2));
>x:= x + 1;
>end loop;
>COMMIT;
>dde.terminate(convid);
>dde.app_end(appid);
>END;
--
Message was edited by:
user575536
any one explains above Procedure please!
I want to copy data from excel sheets files to Oracle 10g. but the problem is all the columns are not same in excel and my oracle table.
that means, i have to copy 8 out of 10 columns of excel to the oracle table and the rest of 3 columns in the table i have to set it ,may be by update statemnet.
anyone has any idea to copy this kind of excel files to oracle?
Thanks
i have a similar issue that I convert oracle application server to unix platform instead of windows platform, and i'm using dde package to exchange data between oracle and microsoft application,now i cant exchange data
anybody could tell me how to use dde with unix plat form please

Labels: , , , , , , ,

how to copy columns into other table

Hi.
I am look for a smart way to copy dataColumn's form one table to an other.
I try to copy all primary key columns to an other table as foreign key
columns.
-> dtNew.Columns.AddRange(dtOld.PrimaryKey) (pseudo example)
This of cause don't work because dtOld.PrimaryKey(0).Table contains
a reference to dtAlt dataTable.
Any Idea?
Greetings TomekHi Tomasz,
The datacolumn does (with execption from a 1 column table) not exist as
dataitem.
In my opinion you have to loop through your old table to copy it.
(And do not do it direct because than you are setting the references and the
values are still in the original).
Cor
Cor Ligthert wrote:
> Hi Tomasz,
> The datacolumn does (with execption from a 1 column table) not exist as
> dataitem.
> In my opinion you have to loop through your old table to copy it.
> (And do not do it direct because than you are setting the references and the
> values are still in the original).
> Cor
>
Hi Cor.
thanks for answer :)
I did it so.
*Tomek*

Labels: , , , , , , , , ,

How to copy an Access database using ADO.NET and C#??

Hi all,
I have an Access '97 database called "dbHLS", inside this database I have a
table called "tbHLS". I would like to copy the table tbHLS from within the
dbHLS.mdb to an Access 2002 database called "dbTarget". Obviously as I'm
copying the table tbHLS I dont want anything to do with the table to change
other than the location of it.
Can this be done? if so how can it be done' Anyone know of any links?
Thanks in advance.
--
Message posted via DotNetMonster.com
http://www.dotnetmonster.com/Uwe/Forums.aspx/dotnet-ado-net/200511/1On Fri, 18 Nov 2005 16:54:31 GMT, "Jon S via DotNetMonster.com" <u2272@.uwe> wrote:
¤ Hi all,
¤
¤ I have an Access '97 database called "dbHLS", inside this database I have a
¤ table called "tbHLS". I would like to copy the table tbHLS from within the
¤ dbHLS.mdb to an Access 2002 database called "dbTarget". Obviously as I'm
¤ copying the table tbHLS I dont want anything to do with the table to change
¤ other than the location of it.
¤
¤ Can this be done? if so how can it be done' Anyone know of any links?
The following code will create the table and copy the data. However, it will not create any indexes
or primary keys, etc.
Function ExportAccessToAccess() As Boolean
Dim AccessConn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"
& _
"Data Source=e:\My Documents\dbHLS.mdb")
AccessConn.Open()
Dim AccessCommand As New System.Data.OleDb.OleDbCommand("SELECT * INTO [MS
Access;DATABASE=E:\My Documents\dbTarget.mdb;].[tbHLS] FROM tbHLS", AccessConn)
AccessCommand.ExecuteNonQuery()
AccessConn.Close()
Paul
~~~~
Microsoft MVP (Visual Basic)

Labels: , , , , , , , , ,

how to Copy a table from mssql to ms access

Is there any way to copy a table(structure and data) from mssql to ms access?
Moved from the C# language group to the .NET Data access and storage group, as that's much more relevant here.
Jon

Labels: , , , , , ,

How to copy a row in a Dataview based on user selection?

I have a datatable that I'm displaying in a Winform Datagrid via a
DataView, and I want the user to be able to right-click on any of the rows
and select a "copy row" command from a context menu. Then I need to make
the copy happen.
I've got the context menu up and responding appropriately, but I'm having
difficulty dealing with the copying:
Firstly, how do I identify what row the user wants to copy?
Second, how do I make a copy of the row? There is no "Clone" method for
a row. Do I need to do an element-by-element copy of the row? And if so,
can I do this with an enumerator or must I use column names?
I've been struggling with this for a half a day; I'd sure appreciate any
help.
--
MichaelMichael,
To find the current dataRow try
DataView dataView = (DataView)((CurrencyManager)
dataGrid1.BindingContext[ dataGrid1.DataSource, dataGrid1.DataMember
]).List;
DataRow dataRow = dataView[ dataGrid1.CurrentRowIndex ].Row;
To copy the row into another dataTable (with the same structure) try
destinationTable.Rows.Add(dataRow.ItemArray);
All the Best,
Phil.
"Michael Kellogg" wrote:
> I have a datatable that I'm displaying in a Winform Datagrid via a
> DataView, and I want the user to be able to right-click on any of the rows
> and select a "copy row" command from a context menu. Then I need to make
> the copy happen.
> I've got the context menu up and responding appropriately, but I'm having
> difficulty dealing with the copying:
> Firstly, how do I identify what row the user wants to copy?
> Second, how do I make a copy of the row? There is no "Clone" method for
> a row. Do I need to do an element-by-element copy of the row? And if so,
> can I do this with an enumerator or must I use column names?
>
> I've been struggling with this for a half a day; I'd sure appreciate any
> help.
> --
> Michael
>
<PhilWilliams@.discussions.microsoft.com> wrote:
> Michael,
> To find the current dataRow try
> DataView dataView = (DataView)((CurrencyManager)
dataGrid1.BindingContext [dataGrid1.DataSource,
dataGrid1.DataMember]).List;
> DataRow dataRow = dataView[ dataGrid1.CurrentRowIndex ].Row;
> To copy the row into another dataTable (with the same structure) try
> destinationTable.Rows.Add(dataRow.ItemArray);
> All the Best,
> Phil.
Thanks for the help, Phil. I'm still trying to understand exactly what
you're doing, here. I've never really understood BindingManagerBase
objects and their function. I like the way you added a copy of a row
without really cloning it; I would not have thought of that.
One issue I'm having is that, when capturing the right-click that brings
up the context menu, if you click on the row itself (the technical term
escapes me; the little box on the left side of a row), the
CurrentRowIndex property does NOT seem to update with that row. You have
to actually click on a cell inside the row. Consequently, the row
returned is wrong. I tried doing a SELECT on the row identified in the
MouseDown event handler (where the use of HitTest will give me the
correct row index), but this doesn't seem to work, either. Is there a
way to "activate" a row so the CurrentRowIndex property is guaranteed to
be right?
Thanks again for the help.
MK
Michael,
In contextMenu_Popup, try
DataGrid.HitTestInfo hti = dataGrid1.HitTest(
dataGrid1.PointToClient(Control.MousePosition));
if (hti.Row != -1)
{
DataView dataView = (DataView)((CurrencyManager)dataGrid1.BindingContext[
dataGrid1.DataSource, dataGrid1.DataMember ]).List;
DataRow dataRow = dataView[ hti.Row ].Row;
}
Cheers,
Phil.
"Michael Kellogg" wrote:
> <PhilWilliams@.discussions.microsoft.com> wrote:
> > Michael,
> > To find the current dataRow try
> >
> > DataView dataView = (DataView)((CurrencyManager)
> dataGrid1.BindingContext [dataGrid1.DataSource,
> dataGrid1.DataMember]).List;
> > DataRow dataRow = dataView[ dataGrid1.CurrentRowIndex ].Row;
> >
> > To copy the row into another dataTable (with the same structure) try
> > destinationTable.Rows.Add(dataRow.ItemArray);
> >
> > All the Best,
> > Phil.
>
> Thanks for the help, Phil. I'm still trying to understand exactly what
> you're doing, here. I've never really understood BindingManagerBase
> objects and their function. I like the way you added a copy of a row
> without really cloning it; I would not have thought of that.
> One issue I'm having is that, when capturing the right-click that brings
> up the context menu, if you click on the row itself (the technical term
> escapes me; the little box on the left side of a row), the
> CurrentRowIndex property does NOT seem to update with that row. You have
> to actually click on a cell inside the row. Consequently, the row
> returned is wrong. I tried doing a SELECT on the row identified in the
> MouseDown event handler (where the use of HitTest will give me the
> correct row index), but this doesn't seem to work, either. Is there a
> way to "activate" a row so the CurrentRowIndex property is guaranteed to
> be right?
> Thanks again for the help.
> MK
>
"=?Utf-8?B?UGhpbCBXaWxsaWFtcw==?="
<PhilWilliams@.discussions.microsoft.com> wrote:
> Michael,
> In contextMenu_Popup, try
> DataGrid.HitTestInfo hti = dataGrid1.HitTest(
> dataGrid1.PointToClient(Control.MousePosition));
> if (hti.Row != -1)
> {
> DataView dataView => (DataView)((CurrencyManager)dataGrid1.BindingContext[
> dataGrid1.DataSource, dataGrid1.DataMember ]).List;
> DataRow dataRow = dataView[ hti.Row ].Row;
> }
That is very clever; I like it. Any chance I can do something like this
in the MenuItem CLICK handler instead (obviously the mouse will have
moved by the time I select a context menu item)? I can get the row using
your method either in the POPUP, as you suggest, or in the datagrid CLICK
handler, as well. Then my thought was to stash the row number in a
member variable and use it in the MenuItem CLICK handler. However, this
didn't seem so elegant to me and I thought it'd be nice to actually
determine the row inside the handler. Am I obsessing?
--
Michael
Michael,
Add the following lines
private int clickedRow = -1;
.
.
.
private void contextMenu_Popup(object sender, System.EventArgs e)
{
DataGrid.HitTestInfo hti = dataGrid1.HitTest(
dataGrid1.PointToClient(Control.MousePosition));
clickedRow = hti.Row;
menuItemCopyRow.Enabled = clickedRow != -1;
}
private void menuItemCopyRow_Click(object sender, System.EventArgs e)
{
if (clickedRow == -1) return;
DataView dataView = (DataView)((CurrencyManager)dataGrid1.BindingContext[
dataGrid1.DataSource, dataGrid1.DataMember ]).List;
DataRow dataRow = dataView[ clickedRow ].Row;
}
All the best,
Phil.
> >
> > if (hti.Row != -1)
"Michael Kellogg" wrote:
> "=?Utf-8?B?UGhpbCBXaWxsaWFtcw==?="
> <PhilWilliams@.discussions.microsoft.com> wrote:
> > Michael,
> > In contextMenu_Popup, try
> >
> > DataGrid.HitTestInfo hti = dataGrid1.HitTest(
> > dataGrid1.PointToClient(Control.MousePosition));
> >
> > if (hti.Row != -1)
> > {
> > DataView dataView => > (DataView)((CurrencyManager)dataGrid1.BindingContext[
> > dataGrid1.DataSource, dataGrid1.DataMember ]).List;
> > DataRow dataRow = dataView[ hti.Row ].Row;
> > }
> That is very clever; I like it. Any chance I can do something like this
> in the MenuItem CLICK handler instead (obviously the mouse will have
> moved by the time I select a context menu item)? I can get the row using
> your method either in the POPUP, as you suggest, or in the datagrid CLICK
> handler, as well. Then my thought was to stash the row number in a
> member variable and use it in the MenuItem CLICK handler. However, this
> didn't seem so elegant to me and I thought it'd be nice to actually
> determine the row inside the handler. Am I obsessing?
> --
> Michael
>
<PhilWilliams@.discussions.microsoft.com> wrote:
> Michael,
> Add the following lines
> private int clickedRow = -1;
> .
> .
> .
> private void contextMenu_Popup(object sender, System.EventArgs e)
> {
> DataGrid.HitTestInfo hti = dataGrid1.HitTest(
> dataGrid1.PointToClient(Control.MousePosition));
> clickedRow = hti.Row;
> menuItemCopyRow.Enabled = clickedRow != -1;
> }
> private void menuItemCopyRow_Click(object sender, System.EventArgs e)
> {
> if (clickedRow == -1) return;
> DataView dataView => (DataView)((CurrencyManager)dataGrid1.BindingContext[
> dataGrid1.DataSource, dataGrid1.DataMember ]).List;
> DataRow dataRow = dataView[ clickedRow ].Row;
> }
> All the best,
> Phil.
Thanks, Phil!
-mk

Labels: , , , , , , , , , , , , , ,

How to copy a row from one DataTable to another DataTable?

Hi all,
Assume that both DataTable are the same schema, I want to copy a row from
one DataTable to another DataTable by
m_dtItem.Rows.Add(m_dtOrgItem.Rows(0))
However, it said that
Exception Details: System.ArgumentException: This row already belongs to
another table.
So, How can copy a row from one DataTable to another DataTable?
Thank you.use m_dtItem.ImportRow instead of m_dtItem.Rows.Add
"angus" <angus@.angus.com> wrote in message
news:ODVqYLWwEHA.1292@.TK2MSFTNGP10.phx.gbl...
> Hi all,
> Assume that both DataTable are the same schema, I want to copy a row from
> one DataTable to another DataTable by
> m_dtItem.Rows.Add(m_dtOrgItem.Rows(0))
> However, it said that
> Exception Details: System.ArgumentException: This row already belongs to
> another table.
> So, How can copy a row from one DataTable to another DataTable?
> Thank you.
>
Hi -
You have to use the ItemArray to copy the row
m_dtItem.Rows.Add(m_dtOrgItem.Rows(0).ItemArray)
Shankar
11/3/2004 10:36:04 AM
angus <angus@.angus.com> wrote in message
<ODVqYLWwEHA.1292@.TK2MSFTNGP10.phx.gbl>
> Hi all,
> Assume that both DataTable are the same schema, I want to copy a
row from
> one DataTable to another DataTable by
> m_dtItem.Rows.Add(m_dtOrgItem.Rows(0))
> However, it said that
> Exception Details: System.ArgumentException: This row already
belongs to
> another table.
> So, How can copy a row from one DataTable to another DataTable?
> Thank you.
Right
To prevent that everybody reads everything again and againg
:-)
> use m_dtItem.ImportRow instead of m_dtItem.Rows.Add
>

Labels: , , , , , ,

How to copy a datatable to another specify column mapping

Hello,

Can any one show me how to copy the data in one datatable to another datatable? For example:

say from tableA .ColumnX to tableB.ColumnY

Thanks in advance for any suggestions.

You may wish to look into the bulk copy class featured in .Net 2.0 this can only be used with SQL Server. You can read morehere

You could also read from your current table and insert ino the new table using another command object. If you are unsure about doing this, reply to this thread and let me know which language you prefer and I'll post an example.

Good Luck


First make sure that the two columns are of the same size.Then may you use the sql statements--"Insert" to add the data column from Table B into Table A.

Maybe what I said was not correct,Please tell me.

Labels: , , , , , , , , , , ,

How to copy a complex query result into a csv in file system

hi

How to copy a complex query result into a csv in file system

Regards

Rajesh

exuberantleon@dotnet.itags.org.yahoo.co.in

You didn't give much details. A way would be:

-Create a text file with csv extension.

-ExecuteReader()

-Write column names on first line separated by commas

while ( reader.Read() )

{

// Write row data, fields separated by commas and " as string delimiter. Each row ends with a CRLF pair

}


It depends on source of the data. In a case of SQL Server, you could write SQL DTS job that does it for you. If you have data in a DataSet, then you could use method described in CetinBasoz post or transform DataSet's XML into CSV using XSL

Labels: , , , , , , , , ,

how to convert to sqltype?

For example there is a DataTable dt and the first column in the firstrow is type of string, I want to assign it to SqlString as following:

SqlString s = (SqlString)dt.Rows[0][0];

The above code throws "Invalid cast" exception. My question is how tocast it to SqlString in this case? In general, how about cast othertypes? such as if the second column in the first row is type ofdecimal, then how to cast it to SqlDecimal?

SqlDecimal d ? dt.Rows[0][1]

Thanks.

I think you could do:

SqlString s = new SqlString(dt.Rows[0][0].ToString());

I'm curious why you're wanting to work with it as a SqlString?

Marcie

Labels: , , , , , , , , , , , ,

How to convert time format

Hi all,

I had query some time information from the database and use a dataset to bind to a GridView.

But unfortunately, the time that display on the GridView is not my desired choice.

It was display as "3/1/2007 10:06:27 PM".

Does anyone know how to convert it as "3/1/2007 22:06:27"?

Part of my code is as follow

pgDataAdapter.Fill(ds,

"Start Time");

Thanks

Hi bslim67,

You can use the DataFormatString property of the GridView column to format the datetime value.

Hope this helps.


Hi,

Hi,

I had tried this.

<asp:BoundFieldDataField="starttime"dataformatstring="{0:dd/MMM/yy}"

HeaderText

="Start Time"ReadOnly="True"SortExpression="starttime"/>

But when I run the program during runtime, it seems that it did not take effect.

It still show me the date and time though my dataformat is only on date.

Please help.

Thanks


Dear , friend:

You should set HtmlEncode=false in the markup of:BoundField

I hope the above information will be helpful. If you have any issues or concerns, please let me know. It's my pleasure to be of assistance


Hi,

Thanks for your info. It's really a great help for me.

Labels: , , , , , , , , , , ,

How to convert text in GridView col into a hyperlink?

Hi,

One of the fields in a GridView control contains a unc path to a local area network folder [eg:\\servername\foldername].

Each record in the GridView may have a path to a different folder.

I would like to be able to click on the path in the GridView and have the folder open - instead of having to copy the text into the Start | Run dialog box of my pc.

I've looked at converting the column into a hyperlink control [by making it a Templated control] & I've tried this code:

<Columns>
<asp:hyperlinkfield datatextfield="Path"
datanavigateurlformatstring="Path"/>
<asp:BoundField DataField="Path"
HeaderText="Online"
SortExpression="Path" />
</Columns>

. . . and I get an error because the app is trying to open a folder in the directory where the web site resides rather than the folder that is indicated in the path [Text] in the column.

I'm trying to figure out how to tell asp.net to open the folder indicated by the unc path in the field . . .Confused

I'd appreciate any help I can get.

Thanks!

Robin

What most likely is happening, is all links in a website by default are relative, so you end up with a link to something like this

http://localhost:12345:\\servername\path

Which obviously isnt going to work. You can fix it by prefixing it with something it recognizes as a file path, rather than a relative path.


Try replacing your <asp:HyperLink /> with this:

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:HyperLinkText="TextField"id="myHL"runat="server"

NavigateUrl='<%# "file:///" + DataBinder.Eval(Container.DataItem, "Path").ToString() %>'></asp:HyperLink>

</ItemTemplate>

</asp:TemplateField>

</Columns>

Thanks, Hans! That worked.

I have one more question, though. In the Text = "TextField" - I would like the text that displays be the actual path that is coming in from the database.

So - instead of TextField [hard-coded literal] in the GridView I'd like it to have something like this -\\ServerName\FolderName [what is in the field for each record].

How would I do that?

Robin


Text='<%# Databinder.Eval(Container.DataITem, "Path").tostring() %>'


Thanks, Bryan. Perfect! I tried playing around with that line of code from Hans . . .

Robin

Labels: , , , , , , , , , , , , , , , , , ,

How to convert 'System.String' to 'System.Guid'

prm = new SqlParameter("@dotnet.itags.org.passkey", SqlDbType.UniqueIdentifier);
prm.Value = stringvalue;
I got this exception
Invalid cast from 'System.String' to 'System.Guid'
--
Arne Garvander
(I program VB.Net for fun and C# to get paid.)prm.Value = new Guid(stringvalue);
"Arne Garvander" <ArneGarvander@.discussions.microsoft.com> wrote in message
news:ACDE0382-BBD1-4AC8-9D99-55445B9F6F49@.microsoft.com...
> prm = new SqlParameter("@.passkey", SqlDbType.UniqueIdentifier);
> prm.Value = stringvalue;
> I got this exception
> Invalid cast from 'System.String' to 'System.Guid'
> --
> Arne Garvander
> (I program VB.Net for fun and C# to get paid.)

Labels: , , , , , , , , , , , , , ,

How to convert strings yymmdd (example: 060120) into regular dates (example: 01/20/06)?

I just want to do this for displaying the data using a gridview. I am working with VB.NET.

The dates need to be saved as they are (strings = yymmdd. example: 060911) so I do not want to save how the are saved in the SQL database.

But I want to display them using the gridview in the standard date format ('mm/dd/yyyy' or 'mm/dd/yy') so I will need to convert them.


I would like to know which would be a nice way to accomplish this, thanks for any suggestions.

another thing i would like to know how to do is to convert another field from the same gridview from string: (example: '2295' into formated amounts (example: $22.95) I do not care wether they are numeric or strings, because I just want it for displaying the data in the gridview. But also these values are saved without the decimal point, for example 10099, should be converted to $100.99 or 150089 should become $1,500.89

Thanks for suggestions.

remember I do not want to change or save this data into the database, because it is supposed to be saved as it is. But I do want to be able to show the user the data in the appropiate format.

The thing is that I do not know how or where to write the code to tell the gridview to convert it how I want it.

This will convert your date to a DateTime object

DateTime.ParseExact("060708","yymmdd", System.Globalization.CultureInfo.CurrentCulture ,System.Globalization.DateTimeStyles.None)

You can handle the RowDataBound event find the label you are displaying it in and set it to something like

mylabel.Text = DateTime.ParseExact("060708","yymmdd", System.Globalization.CultureInfo.CurrentCulture ,System.Globalization.DateTimeStyles.None).ToString("mm/dd/yyy")


I need help doing the rowdatabound for doing that formating

Protected Sub GridView1_RowDataBound(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.GridViewRowEventArgs)Handles GridView1.RowDataBoundTry If e.Row.RowType = DataControlRowType.DataRowThen Dim DollarAmountAs Label =CType(e.Row.FindControl("Label"), Label)
'Here I want to format the current string.text attribute. (how can i do it?)End If Catch End Try End Sub

You can try the solution above;

dim temp as string= DollarAmount.Text

DollarAmount.Text = DateTime.ParseExact(temp,"yymmdd", System.Globalization.CultureInfo.CurrentCulture ,System.Globalization.DateTimeStyles.None).ToString("mm/dd/yyy")


Thanks,Big Smile

Labels: , , , , , , , , , , ,

How to convert string to int n gridview colors?

1st question on vb how do i convert string to int?

2nd question

eg.

GridView1.BorderColor = Drawing.Color.Aqua

its set on vb script but what i want to know is how to make it use color codes for eg. GridView1.BorderColor = #FFFFFF

thank you

Answer 1:

You can use either

int myInt =Integer.Parse(myString)

or

Dim myIntAs IntegerIf Integer.TryParse(myString,out myIntThen Return IntegerElse Return 0End If

Answer 2,

Dim cAs System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#F5F7F8")Dim strHtmlColorAs String = System.Drawing.ColorTranslator.ToHtml(c)

1) Have a look at the Cint, Convert.ToInt16, Integer.Parse or Integer.TryParse methods

2) System.Drawing.Color.FromName("#FFFFFF")

Labels: , , , , , , , , , , , , , ,

How to convert string data into time format

I have some of the old data looks like this. And this is time data.

144601
170320
083345

I wanted to convert this in proper format as time with AM, PM etc. and display in GridView column.

Currently this data is displaying as it is in one of the GridView column

Please help out..

thanks

Public Function stringtodate(ByVal strdate As String) Dim tempdt As Date tempdt = Convert.ToDateTime(strdate) Dim format1 As String Dim en As New CultureInfo("en-AU") format1 = "MM/dd/yyyy HH:mm:ss" Dim dtstring As String dtstring = tempdt.ToString(format1) tempdt = DateTime.ParseExact(dtstring, format1, en.DateTimeFormat) Return tempdt End Function

you can specify the format as u need.

How do I call this function in gridview, to display the data in one of the column of the grid view. ?


Use Bound column of grid.Now in datafield property try to bind the data using a literal.

<asp:literal id="datevar" runat="server">

<asp:grid>

<asp:boundcolumn ......datafield=<%= datevar %>

</asp:grid>

Now in code behind try to bind the your date value by calling that function to the datevar literal in grid_databound event.

Labels: , , , , , , , ,

how to convert sqldatasource to other type like dataview, dataset or datareader

Hi all,

i have got many problems with sqldatasource and dataview

--------------------------------
string ConnectionString = "Server=server;Integrated
Security=True;Database=contest;Persist Security Info=True";

string QueryString = "SELECT * FROM [members]";

System.Web.UI.WebControls.SqlDataSource SqlDataSource = new System.Web.UI.WebControls.SqlDataSource();

SqlDataSource.ConnectionString = ConnectionString;
SqlDataSource.SelectCommand = QueryString;
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataSet;

DataView dv = new DataView();

dv = (DataView)SqlDataSource;
--------------------------------

CS0030: Cannot convert type 'System.Web.UI.WebControls.SqlDataSource' to 'System.Data.DataView'

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

i got similar problems if i use DataSet and DataReader.
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataSet;
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataReader;

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

thx a lot.To return the DataSet from the SqlDataSource you have to use the SqlDataSource Select method. The Select method will return a DataView if the DataSourceMode of the SqlDataSource is set to System.Web.UI.WebControls.SqlDataSourceMode.DataSet.

If you set the mode to System.Web.UI.WebControls.SqlDataSourceMode.DataReader. A DataReader will be returned.
thx,
but, i dont know how to use sqldatasource as dataview after set it to dataset.
u have an example ?
thx
What is your purpose with the code? Do you only want to access a data source and get a Dataset back? If so I should recommend you to use SqlDataAdaptar:


DataSet ds = new DataSet();

using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", myConnectionString))
{
adapter.Fill(ds);
}

If you want to use SqlDataSource for some reason, here is an example:


string ConnectionString = "Server=localhost;Integrated Security=True;Database=Northwind;User=****;password=****;";
string QueryString = "SELECT * FROM [Employees]";
System.Web.UI.WebControls.SqlDataSource SqlDataSource = new System.Web.UI.WebControls.SqlDataSource();
SqlDataSource.ConnectionString = ConnectionString;
SqlDataSource.SelectCommand = QueryString;

DataSourceSelectArguments arg = new DataSourceSelectArguments();
System.Data.DataView dv = (System.Data.DataView)SqlDataSource.Select(arg);


okay thanks, now continuing on with system.data.dataview dv = ..., how do you retrieve a value, can you finish the code for us?
Many thanks,
Asaf

Here is the thing

DataView dv ;

dv = (DataView)DsOpenOrders.Select(DataSourceSelectArguments.Empty);

dv.Sort = SortField;

return dv;

DsOpenOrders is the SqlDataSource.

THis will help you I guess.

Thanks
Suda

Labels: , , , , , , , , ,

How to convert SqlDatareader to DataTable

Hello all,

Is there a way to convert a SqlDatareader to DataTable?

I'm not talking about looping through the datareader and add each value into the datatable. For example the dataset, you use a DataAdapter to fill the data into the dataset.

I've read on something like a ovrride the fill function and of the DbDataAdapter ... but it doesn't seem to work ...

protected overridable function(dataTable as DataTable, dataReader as IDataReader) as integer
return Fill(dataTable, dataReader)
end function

Has anyone done this before? Any input is appreciated.

Unfortunately, as far as I know, the answer is no - due to the inherent nature of a DataReader itself. It's a forward only/read once process. If you don't do something with it at the time it's being created, it's gone.

The only way I can think of to take care of that, would be to manually insert the objects into the datatable, as the datareader was being read


David, your icon is scary ... lol. thanks for the respond. please take a peek at this URL:http://msdn2.microsoft.com/en-us/library/497b1k4t.aspx

and also this sample:http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=628

I tried but somehow I can't get it to run. Well, I didn't copy all of the author's code. What do you think?

Labels: , , , , , , , ,

how to convert objectdatasource to dataView?

hi there...does anyone run into a problem where the objectdatasource cannot be casting into dataview? it aleays works for me except for this time

.csDataView dv = (DataView)objSubCategoriesByUserPermissions.Select();.aspx<asp:ObjectDataSource ID="objSubCategoriesByUserPermissions" runat="server" SelectMethod="GetCategoryByUserPermissions" TypeName="MB.TheBeerHouse.BLL.Articles.Category"> <SelectParameters> <asp:QueryStringParameter Name="articleID" QueryStringField="ID" DefaultValue="-1" /> <asp:ProfileParameter Name="username" PropertyName="username" /> </SelectParameters> </asp:ObjectDataSource> <br /> <asp:SqlDataSource ID="sdcAllCategories" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString%>" SelectCommand="SELECT CategoryID, Title FROM tbh_Categories WHERE (visible = 1) AND (ParentID IS NULL)"> </asp:SqlDataSource>

Unable to cast object of type 'System.Object[]' to type 'System.Data.DataView'.

Hi

ObjectDataSource.select() must return one of the types listed below:

IEnumerable

TheIEnumerable is returned by theSelect method.

DataTable

ADataView is created by using theDataTable and returned by theSelect method.

DataView

TheDataView is returned by theSelect method.

DataSet

The firstDataTable of theDataSet is extracted and aDataView is created and returned by theSelect method.

Object

The object is wrapped in a one-elementIEnumerable collection and returned by theSelect method.

Here is a similar thread that may give you clue:http://forums.asp.net/thread/1491464.aspx

For details about ObjectDataSource.select() seehttp://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.select.aspx

Hope this helps.


thank it does.

Labels: , , , , , , ,

How to convert lower case to upper case

Hi everyone

How can I convert lower case to upper case when i type inside a textbox

Please provide me with vb.net code

Do you mean you want to convert it as it is being typed? Or once you receive it on the server-side?

If the latter, use the string.ToUpper() method in VB.NET.http://support.microsoft.com/kb/312897 If the former, you can use the javascript ToUppercase() method in conjunction with the onkeypress event for the textbox in question.http://jennifermadden.com/javascript/stringUpperLower.html


To achieve this on the Client side try this:

add this to your Code behind (VB.net):

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

TextBox1.Attributes.Add("onkeyup","toUppercase()")

EndSub

Then in your HTML markup:

<headrunat="server">
<script
>
function
toUppercase() {
document.form1.TextBox1.value = document.form1.TextBox1.value.toUpperCase();
}
</script
>
</head
>
<body
>
<formid="form1"runat
="server">
<div
>
<asp:TextBoxID="TextBox1"runat="server"></asp:TextBox
>
</div
>
</form
>
</body
>

If you want to do this Server Side (VB.net):

TextBox1.Text = TextBox1.Text.ToUpper



you can use style instead..

<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.test
{
text-transform: uppercase;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div
</div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="test"></asp:TextBox>
</form>
</body>


kaushalparik27:

you can use style instead..

 .test
{
text-transform: uppercase;
}

That won't convert it. It will only change the way it appears on a web page. If you look at the source of the page where your style is used, you will see that the case of the text is still in its original state.


It works, but it saves the data with lower case in the database


have you tried this:

scott@.elbandit.co.uk:

To achieve this on the Client side try this:

add this to your Code behind (VB.net):

ProtectedSub Page_Load(ByVal senderAsObject,ByVal eAs System.EventArgs)HandlesMe.Load

TextBox1.Attributes.Add("onkeyup","toUppercase()")

EndSub

Then in your HTML markup:

<headrunat="server">
<script
>
function
toUppercase() {
document.form1.TextBox1.value = document.form1.TextBox1.value.toUpperCase();
}
</script
>
</head
>
<body
>
<formid="form1"runat
="server">
<div
>
<asp:TextBoxID="TextBox1"runat="server"></asp:TextBox
>
</div
>
</form
>
</body
>

If you want to do this Server Side (VB.net):

TextBox1.Text = TextBox1.Text.ToUpper



pam.rose:

but it saves the data with lower case in the database

but at the time of saving in the database.. simply .ToString().ToUpper() can be used...

Labels: , , , , , , , , ,

How to convert from UserId to UserName in GridView?

i am using membership, and my GridView are using by choosing ObjectDataSource , In my ObjectDataSource i am using UserId, but when show the GridView i want the UserId changer UserName.How to do it? For example my some code,

<asp:TemplateField HeaderText="UserId"><ItemTemplate><%#Eval("UserId")%></ItemTemplate></asp:TemplateField>

You could write method that calls

MembershipUser u =Membership.GetUser(userID);.

username = u.UserName

Then call it from the template with <%# (String) MyGetUserNameMethod(String userid) %>

(declare the function protected string MyGetUseNameMethod in your code behind class)


Dear Sir,

Sorry i still can not understand!


hi

try this

<asp:TemplateField> <ItemTemplate><%#Membership.GetUser(Eval("UserId")).UserName%> </ItemTemplate> </asp:TemplateField>

Dear Sir,

Still can not!


hi

just replace your code with the one i gave you

so delete your templateField column and put my code

man if you still dont understand ,

could you explain what is the things that makes you confused

thanks


Dear Sir,

Thank!!it working,Sorry Sir, maybe just now i am typing wrong, Now, i am no error, Finally Thank you Sir!!!

Labels: , , , , , , , ,

How to Convert from OleDbParametersCollection to OleDbParameter[] array?

I am trying to convert from OleDbParametersCollection object to OleDbParameter[] array. How to perform this operation(ConvertToOleDbParameter())?

What is the problem with the following code? :

Code Snippet

private OleDbParameter[] ConvertToOleDbParameter(OleDbParameterCollection paramCollection)

{

OleDbParameter[] paramArray = new OleDbParameter[paramCollection.Count];

OleDbParameter param = new OleDbParameter();

paramArray.Initialize();

IEnumerator enumParams = paramCollection.GetEnumerator();

for (int i = 0; i < paramCollection.Count; i++)

{

try

{

enumParams.MoveNext();

param = (OleDbParameter) enumParams.Current;

paramArray[i] = param;

}

catch (Exception e)

{

MessageBox.Show(e.Message);

}

}

return paramArray;

}

So, when I do following:

Code Snippet

//....

try

{

OleDbParameter[] arrParams = ConvertToOleDbParameter(paramCollection);

oleCommand.Parameters.AddRange(arrParams);

oleCommand.ExecuteNonQuery();

return true;

}

catch (Exception exc)

{

System.Windows.Forms.MessageBox.Show(exc.Message);

return false;

}

The above throws the following exception:

The OleDbParameter is already contained by another OleDbParameterCollection.

I would appreciate your help.

Thanks.

oleCommand.Parameters is also a OledDbParameterCollection. Your conversion method merely returns an array whose elements are references of the existing parameters in paramCollection. The AddRange() call tries to add those parameters in paramCollection to another parametercollection (oleCommand.Parameters).

The error message tells you that for any parameter, it can only belong to one parametercollection.

Labels: , , , , , , , , ,

How to convert empty string to Null of Datetime data type

Hi,
This is very annoying to me.
I have a datatable which has two fields of DateTime data type. Both of them are nullable. When I do the update to that datatable, in some cases, Null values are going be put through TextBox and DropDownList's selected Item. But the updated value in database is 01/01/1900 and 12:00 AM which is not the real null value, can anyone help me with this?
My update code:

Dim inputDateAsNewDate
Dim inputSessionAsNewDate

If Trim(txtDate.Text) <> ""Then
inputDate = Convert.ToDateTime(txtDate.Text)
Else
inputDate = System.Data.SqlTypes.SqlDateTime.Null -->01/01/1900
EndIf

If ddlSession.SelectedItem.Text <> ""Then
inputSession = Convert.ToDateTime(ddlSession.SelectedItem.Text)
Else
inputSession = System.Data.SqlTypes.SqlDateTime.Null -->12:00 AM
EndIf

UpdateDT(AgendaItemID, inputDate, inputSession)

Just out of interest, why aren't inputSession and input of type Date System.Data.SqlTypes.SqlDateTime?
If you use the standard CLR DateTime structure, it will also run back to its default value as that's all it can hold.
Make the variables of the appropriate type and then convert the input into SqlDateTime, not the other way around, and your problem should go away.

Labels: , , , , , , , , , , , ,

how to convert dBase Database to Access-SQL Database in ASP.Net

I'm developing a project which the data is output from other application (windows application) in form of dBase Database (DBF), i need to convert it into an access/sql data by using asp.net so i can manipulate. please anyone tell me how.

Thank you.

ApcYou could use ADO.NET and the ODBC or OleDb providers (as appropriate - I do not know what the status of drivers for dBase is these days).

At that point, just read it in and write it out...
I use OleDBConnection with Microsoft OLE DB Provider for ODBC Drivers with this properties :
- Use data source name : dBASE Files
- Enter the initial catalog to use : "myprojectpath"

but then I encounter this error :

"The .Net Data OLE DB Provider(System.Data.OleDb) does not support the MSDASQL
Provider, Microsoft OLE DB Provider for ODBC Drivers."

Can you tell me how to solve this problem.

Thank you.
Use the .NET ODBC provider. Using .NET 1.1, the ODBC provider should already be installed. It has classes that mirror SqlClient and OleDb.

Labels: , , , , , , , , , , , , ,

How to convert dataset to xml string with embedded schema

I have been trying to find a way to get an xml string with embedded schema from a dataset.

I know that you can use the .getxml and .getschema functions on the dataset but I do not see an easy way of combining those two results into one valid xml string.

I can't save anything to disk, everything has to happen in memory. I thought of using the .writexml method but you cannot use .writexml and pass a string...

Thank you for any thoughts you might have to solve this problem I am having.

Robertmaybe u can use the XmlSerializer object?

Labels: , , , , , , , , ,

How to convert datareader.items value to integer

Hi,

I have a datareader item

myreader.Item("netcost")

This is a numeric value, I need to take the value and minus 500 from it, I have

(myreader.Item("netcost")-500)

This causes an error, 'cannot cast from string to integer'

How do I do it?

Thanks. BenYou can use Ctype.

For example, this converts you datareader item to an integer.

CType(myreader.Item("netcost"),Integer) - 500
Convert.ToInt32(myreader.Item("netcost").ToString())

Labels: , , , , , , , , , , ,

how to convert DataColumn to string array

Dear friends,

How to convert DataColumn to String Array

I have a set of values in DataColumn that values should be transferred to String Array. Is there any sort way without using looping statement.

Thanks.

I think there is no other alternative than looping the table .. a similar stuff is discussed and can be used

http://dotnet.org.za/keithrull/archive/2006/01/13/38913.aspx


Hi,

If you just need to get the values in each DataColumn in a DataRow, there is an ItemArray property for DataRow class. You can go through each row and call DataRow.ItemArray property to get it.

Here is a link for more information

http://msdn2.microsoft.com/en-us/library/system.data.datarow.itemarray.aspx

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!

Labels: , , , , , , , , , ,

How to convert database MS Access to oracle?

How to convert database MS Access to oracle?

My database in MS access 2003. and i want to convert that database in to ORACLE 8i. please guide me for the same. thanks in advance.

You will have to do it manually.

First, create your tables in Oracle.
Next, Export your Access data to a CSV file.
Then use the Oracle command line took, Sql Loader to inport your data from the CSV file into your new Oracle tables.

No you don't.

There are tools by Oracle as well as all kinds of other vendors to do this automatically.

Start here:

http://www.oracle.com/technology/tech/migration/focusareas/access.html


ASPDavid wrote:

No you don't.

There are tools by Oracle as well as all kinds of other vendors to do this automatically.

Start here:

http://www.oracle.com/technology/tech/migration/focusareas/access.html


Thanks for the liink. I wasn't aware Oracle had a tool for importing Access files.

However, I don't ever recommend third-party tools since they involve $$$.
SQL Loader had worked fine for me for years.
dweezil.....can you be more specific...pls....
I have the same problem and I can't find a surce code aniware........can you help me with some....[-o<

BRUX wrote:

dweezil.....can you be more specific...pls....
I have the same problem and I can't find a surce code aniware........can you help me with some....[-o<


Export your Access database to a csv file or whatever file extension you want to use.
Create a corresponding table in Oracle.
Create a control for SQL*Loader:
Load Data
INFILE 'c:\mydatafile.csv
INTO table my_oracle_table_name
fields terminated by "," optionally enclosed by '"'
(
column_1,
column_2
)


Save the above control file as: access.ctl

Open a command prompt and type:
set oracle_sid = myoracle_sid
sqlldr username/password control= access.ctl log=mydatafile.log

Check the log file for any records that failed.

Also, look at Oracle's free developer tool,SQL Developer. I believe it has SQL*Loader funcitionality in it.

Good luck!

Labels: , , , , , , ,