Ask a question
Quick access
- Forums home
- Browse forums users
- FAQ
Search related threads
- Remove From My Forums
Answered by:
Archived Forums 421-440
>
Visual C#
Question
-
Sign in to vote
I need to pass/retrieve as string array object, but I am getting errors with my current effort:
private string[] fldNames()
{
string[] s1 = new string[5];
for (int i = 0; i <= 5; i++)
s1[i] = i.ToString();
return s1;
}private void button3_Click(object sender, EventArgs e)
{
string[] t1 = new string[5];
t1 = fldNames; //<---errors says something about needing a delegate to do this
}how do I pass/call fldNames and assign it to t1? Specifically, I have a class library that I am using for com (VBA). I really need to pass this string array object to VBA. The library is working OK with VBAexcept I need to add a function that passes a list of table fieldnames to a VBA var. How do I perform the above operation in C#?
thanks,
Rich P
Wednesday, August 3, 2011 7:47 PM
Reply
|
Quote
Answers
-
Sign in to vote
What happens if you use a 1-based array?
privateArray fldNames(){ Array s1 = Array.CreateInstance(typeof(string),new[] { 5 },new[] { 1 });for(inti = 1; i <= 5; i++) s1.SetValue(i.ToString(), i);returns1;}private voidbutton3_Click(objectsender, EventArgs e){ Array t1 = fldNames();}
- Marked as answer by Rich P123 Thursday, August 4, 2011 7:17 PM
Thursday, August 4, 2011 9:10 AM
Reply
|
Quote
All replies
-
Sign in to vote
Should be:t1 = fldNames();
Notice the brackets.
Wednesday, August 3, 2011 7:51 PM
Reply
|
Quote
-
Sign in to vote
There are actually two issues here. First, in your fldNames method, you need to initialize this to a length of 6, not 5, since your for loop uses i <= 5 (this will happen for 0,1,2,3,4,5, which is 6 items long). Try this:
private string[] fldNames(){string[] s1 =new string[6];// Construct as an array of 6 elements for(inti = 0; i <= 5; i++) s1[i] = i.ToString();returns1;}
Second, the error you're receiving is because you're putting in the name of the method, notcallingthe method. Also, since your method creates the array, you don't need to initailize it, just set it. Try this:private voidbutton3_Click(objectsender, EventArgs e){string[] t1;// No need to initialize, since it's being set in the next linet1 = fldNames();// Add parenthesis to call the method}
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Proposed as answer by Pantelis44999 Wednesday, August 3, 2011 8:03 PM
Wednesday, August 3, 2011 7:59 PM
Reply
|
Quote
-
Sign in to vote
Good catch Reed, didn't notice the loop problem.
Wednesday, August 3, 2011 8:03 PM
Reply
|
Quote
-
Sign in to vote
thank you all for your replies. Of course, the old () missing. Well, this is now working correctly in C#. Sadly, though, in VBA it is still complaining saying that something is outside the bounds of the array. Here is what I try in VBA
Dim t As Variant
Dim x1 = New myLib.myClass //<--this is the C# Library I created
Redim t(13)
t = x1.fldNames //<--- says index is outside of the array bounds. It isn't, reallyI tried to iterate x1.fldNames in VBA, but I got the same error message. I can pass/retrieve data that is not in array form OK to VBA, strings, ints. I need/want to pass a stringarray object to the VBA var. Anyone have an idea how this could be done? Should I use a list maybe? an Ilist?
Rich P
Wednesday, August 3, 2011 8:42 PM
Reply
|
Quote
-
Sign in to vote
You're not showing all of your code, but the problem may be due to the differences in how .NET handles arrays from VBA. In VBA, arrays start at 1, not 0.
The code you have above isn't actually reading from the array, so it's difficult to know what the problem would be from seeing just that VBA snippet...
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".Wednesday, August 3, 2011 9:35 PM
Reply
|
Quote
-
Sign in to vote
We need more info to fully assist you. I am beginning to suspect that your question is outside of therealm of experienceof most participants on this forum.
CallingVisual Basic for Applications Code from Visual Basic .NET
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971."
http://thesharpercoder.blogspot.com/
Wednesday, August 3, 2011 10:07 PM
Reply
|
Quote
-
Sign in to vote
Well, I came up with one hack where I concatenate the table fieldnames into one string var separated by commasin the class library, and I pass this string to VBA. Then I parse the string out in VBA with the Split function. This is sort of working, but kinda hacky. Below is the source code for the VBA and for my com Class Library.
Sub VBAcode()
Dim x1 As New Database_COMObject.DBCOM_Class
Dim v As Variant, w As Variant, s1 As String, s2() As String
Dim iCols As Integer, i As Integerv = x1.ExecuteSelectCommand("Select * From Orders Where CustomerID = 'VINET'")
If v = True Then
iCols = x1.GetColumnCnt
Debug.Print iCols
iCols = iCols - 1
s1 = x1.fldNames'--thefldNames hack function below
s2 = Split(s1, ",")
For i = 0 To UBound(s2)
Debug.Print s2(i)
Next
End If
End Sub//--C# source code sample from internet for com class library
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;namespace Database_COMObject
{
[Guid("694C1820-04B6-4988-928F-FD858B95C880")]
public interface DBCOM_Interface
{
[DispId(1)]
void Init(string userid , string password);
[DispId(2)]
bool ExecuteSelectCommand(string selCommand);
[DispId(3)]
bool NextRow();
[DispId(4)]
void ExecuteNonSelectCommand(string insCommand);
[DispId(5)]
string GetColumnData(int pos);
[DispId(6)]
int GetColumnCnt();
[DispId(7)]
string fldNames();
}// // Events interface Database_COMObjectEvents
[Guid("47C976E0-C208-4740-AC42-41212D3C34F0"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface DBCOM_Events
{
}
[Guid("9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(DBCOM_Events))]
public class DBCOM_Class : DBCOM_Interface
{
private SqlConnection myConnection = null ;
SqlDataReader myReader = null ;public DBCOM_Class()
{
}public void Init(string userid , string password)
{
try
{
//string myConnectString = "user id="+userid+";password="+password+
// ";Database=NorthWind;Server=COMP10\\SQL2008R2;Connect Timeout=30";//string myConnectString = "Data Source=COMP10\\SQL2008R2;Initial Catalog=NorthWind;Integrated Security=True;Connect Timeout=30";
//myConnection = new SqlConnection(myConnectString);
//myConnection.Open();
//MessageBox.Show("CONNECTED");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}public bool ExecuteSelectCommand(string selCommand)
{
if ( myReader != null )
myReader.Close() ;string myConnectString = "Data Source=COMP10\\SQL2008R2;Initial Catalog=NorthWind;Integrated Security=True;Connect Timeout=30";
myConnection = new SqlConnection(myConnectString);
myConnection.Open();SqlCommand myCommand = new SqlCommand(selCommand);
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myReader = myCommand.ExecuteReader();
return true ;
}
public bool NextRow()
{
if ( ! myReader.Read() )
{
myReader.Close();
return false ;
}
return true ;
}public string GetColumnData(int pos)
{
Object obj = myReader.GetValue(pos);
if ( obj == null ) return "" ;
return obj.ToString() ;
}public int GetColumnCnt()
{
return myReader.FieldCount;
}public string fldNames()
{ //--mystring array hack
int i = myReader.FieldCount - 1;
string flds = myReader.GetName(0);
for (int j = 1; j <= i; j++)
flds += "," + myReader.GetName(j);
return flds;
}public void ExecuteNonSelectCommand(string insCommand)
{
SqlCommand myCommand = new SqlCommand(insCommand , myConnection);
int retRows = myCommand.ExecuteNonQuery();
}}
}Rich P
Wednesday, August 3, 2011 10:12 PM
Reply
|
Quote
-
Sign in to vote
What happens if you remove :Redim t(13)
It looks to me like you're passing an 7 element array to an array that's sized for 13. Not sure how VBA would handle that.
Wednesday, August 3, 2011 10:22 PM
Reply
|
Quote
-
Sign in to vote
I have tried all sorts of iterations of an array object in VBA to receive the array object from the C# com Library -- to no avail. The only thing that is working right now is my string concatenate hack. Eventually, I would like to pass the whole (.Net) table to (Excel) VBA - same as com ADO where you can say Sheet1.Range("A1").CopyFromRecordset RS where RS is an ADODB recordset object. I'm trying to encapsulate as much functionality in my com Lib file as possible to reduce the amount of VBA coding for this project. Some things are easier to perform in C#.
Rich P
Wednesday, August 3, 2011 10:38 PM
Reply
|
Quote
-
Sign in to vote
What happens if you use a 1-based array?
privateArray fldNames(){ Array s1 = Array.CreateInstance(typeof(string),new[] { 5 },new[] { 1 });for(inti = 1; i <= 5; i++) s1.SetValue(i.ToString(), i);returns1;}private voidbutton3_Click(objectsender, EventArgs e){ Array t1 = fldNames();}
- Marked as answer by Rich P123 Thursday, August 4, 2011 7:17 PM
Thursday, August 4, 2011 9:10 AM
Reply
|
Quote
-
Sign in to vote
What happens if you use a 1-based array?
privateArray fldNames()
{ Array s1 = Array.CreateInstance(typeof(string),new[] { 5 },new[] { 1 });
for(inti = 1; i <= 5; i++)
s1.SetValue(i.ToString(), i);
returns1; }
private voidbutton3_Click(objectsender, EventArgs e)
{
Array t1 = fldNames();
}
thanks. How do I write/extract the contents of t1 to the console? I tried a for loop --- Console.WriteLine(t1[i]); --- not working.
Rich P
Thursday, August 4, 2011 3:36 PM
Reply
|
Quote
-
Sign in to vote
Console.WriteLine(t1.GetValue(i));
Thursday, August 4, 2011 4:26 PM
Reply
|
Quote
-
Sign in to vote
Thanks. I tried the Array fldNames idea. I named it fldNames2. At least now in VBA the variant t is taking x1.fldNames2. But t is getting only a System.Object[] value from x1.fldNames2. Now I have to find out if there is a way I can tap into System.Object[] from VBA.
Rich P
Thursday, August 4, 2011 5:18 PM
Reply
|
Quote
-
Sign in to vote
Yay! I did it! Here's the (Excel)VBA code I used -- and thanks for the idea of using Array fldNames instead of string[] fldNames. That did the trick!
Sub slsl()
Dim x1 As New Database_COMObject.DBCOM_Class
Dim icol As Integer, i As Integer, j As Integer
Dim v As Variant, w As Variant, t As Variant, u As Variant, s As Variant
v = x1.ExecuteSelectCommand("Select * From Orders Where CustomerID = 'VINET'")
If v = True Then
w = x1.NextRow
If w = True Then
i = x1.GetColumnCnt
Debug.Print i
t = Array(x1.fldNames2)
For Each u In t
Debug.Print u
For Each s In u
Debug.Print "*" & s & "*"
Next
Next
End If
End If
End SubNote: it doesn't matter if it is 1 based or 0 based array. I used a 0 based array.
Rich P
Thursday, August 4, 2011 5:25 PM
Reply
|
Quote
FAQs
How do you return an array from a function? ›
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
How to return an array of object from a function in Java? ›We can also pass an array as a parameter as well as return the array from the particular user-defined or predefined function. To return an array in Java, you can simply include the array as the return type of a method.
How do you return an array object in Python? ›A Python function can return any object such as a NumPy Array. To return an array, first create the array object within the function body, assign it to a variable arr , and return it to the caller of the function using the keyword operation “ return arr “.
How to return one object from array in JavaScript? ›You need to use the index for the array. Then you need only a check if isAstronaut is true and return with the item. At the end outside of the for loop, return null , for a not found astronaut. If you check inside the loop, you will return too early with the wrong result.
How to return an array element from a function in C? ›- #include <stdio.h>
- int *getarray(int *a)
- {
- printf("Enter the elements in an array : ");
- for(int i=0;i<5;i++)
- {
- scanf("%d", &a[i]);
- }
Arrays can be returned from functions in C using a pointer pointing to the base address of the array or by creating a user-defined data type using struct. To pass a multidimensional array to function, it is important to pass all dimensions of the array except the first dimension.
How to return an object from a function in Java? ›In java, a method can return any type of data, including objects. For example, in the following program, the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the invoking object.
Can we return an array of object? ›1 Answer. To explain: The Object array can be returned from a function. This can be done by putting a className* as the return type of the function. This makes the return type to accept an array of objects in return.
How to receive array of objects in Java? ›An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.
Which method is used to return a array? ›We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
How to return an array from a function in Visual Basic? ›
To return an array from a Function procedure, specify the array data type and the number of dimensions as the return type of the Function Statement. Within the function, declare a local array variable with same data type and number of dimensions.
How to return 2D array from function in C? ›- Using Dynamic Array.
- Using Static Keyword.
- Using Struct technique.
To return an array from a function in JavaScript, define an object with the help of the “Array()” constructor and store the data on each index. Then, use the “return” statement with the defined variable. Furthermore, you can store the data in variables and return it in the array with the “return” statement.