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: , , , , , , , , , , ,