How to copy strings in array of strings....I am getting some errors....

Hi,

I want to display all the file names that are present in a specified directory....say "C:\data" in a GridView

for that I am using the following:

Imports System.IO

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim strFileSize As String = ""

Dim di As New IO.DirectoryInfo("C:\data")

Dim aryFi As IO.FileInfo() = di.GetFiles()

Dim fi As IO.FileInfo

For Each fi In aryFi

strFileSize = (Math.Round(fi.Length / 1024)).ToString()

Response.Write(fi.Name)

 

Next

GridView1.DataSource = aryFi

GridView1.DataBind()

End Sub

End Class

But the problem is that the array "aryFi" contains all other information about the files....like date created,size,extension,last modified etc apart from file name and full file name (along with path)

when I display the info in "aryFi" by setting it as the datasource of GridView1.... all the fields are displaying....like date created,size,extension,last modified etc apart from file name and full file name....but I want only file name to be displayed in the GridView...

So, what i thought was to have an array say "array_files" of string and copy only the file name in it during every iteration....

and in the end set "array_files" as the datasource of GridView1....

Something like this

Imports System.IO

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim strFileSize As String = ""

Dim di As New IO.DirectoryInfo("C:\data")

Dim aryFi As IO.FileInfo() = di.GetFiles()

'Dim array_file(10) As String //array of strings.... 'Dim i As Integer // index of the array_files...

Dim fi As IO.FileInfo

' i = 0 //initialize i as zero

For Each fi In aryFi

strFileSize = (Math.Round(fi.Length / 1024)).ToString()

'array_file(i) = fi.Name //simply store fi.Name field in array_files(i) in ith index...

'i = i + 1   ///incrementing i

Response.Write(fi.Name)

 

Next

'GridView1.DataSource = array_files //setting array_files that holds only file names as the datasource of GridView1

'GridView1.DataBind()

End Sub

End Class

BUT I AM GETTING THE FOLLOWING COMPILE TIME ERROR

Variable 'array_files' is used before it has been assigned a value. A null reference exception could result at runtime.

 

PLEASE TELL ME HOW TO RESOLVE THIS PROBLEM...I THINK THERE IS SOME SYNTAX ERROR WHILE DECLARING OR STORING IN ARRAY

ANY HELP WILL BE HIGHLY APPRECIATED....

THANKS..

 

 

0
ramkunchur
6/11/2008 4:32:08 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

7 Replies
857 Views

Similar Articles

[PageSpeed] 42

FileInfo.Name returns the name of the file

FileInfo.Path returns the full path of the file

By default, a Gridview will display all columns available in the data source. You're on the right track with your first approach, i.e. bind the datagrid with the result from GetFiles. However, what you need to do is to configure the GridView to only display the columns you are interested in.

The relevant changes you need to do to your GridView (in aspx) are these:

<asp:GridView AutoGenerateColumns="False" ... >
  <Columns>
    <asp:BoundField DataField="Path" HeaderText="Path"/>
    <asp:BoundField DataField="Length" HeaderText="Length"/>
  </Columns>
</asp:GridView>
This will allow the GridView to only display path and length when you bind it to the file list you get from GetFiles.
If this post was useful to you, please mark it as answer. Thank you!
0
johram
6/11/2008 5:03:16 AM

Hi,

I think, you use DataTable instead of Array to store the values and bind it to the GridView control.

Dim dt As New DataTable()

dt.Columns.Add("Folder", GetType(String))

dt.Columns.Add("FileName", GetType(String))

Dim r As DataRow

For Each info As IO.FileInfo In New IO.DirectoryInfo("C:\Inetpub\wwwroot").GetFiles

r = dt.NewRow()

r(
"Folder") = info.DirectoryNamer("FileName") = info.Name

dt.Rows.Add(r)

Next

Me.GridView1.DataSource = dt

Me.GridView1.DataBind()

Hope this helps.

Regards,

Manish 

 

 

 


Manish Singhal
www.ComponentOne.com
0
manish
6/11/2008 5:16:21 AM

hey johram....

There is no such line as

<asp:GridView AutoGenerateColumns="False" ... >

in my aspx....

What to do?

And I want to display only Name & LastAccessTime and not Path and Length....

Please reply....

Thanks

0
ramkunchur
6/11/2008 5:44:19 AM

Hi manish...

Thanks for ur help

But I am getting an error on this line

r("Folder") = info.DirectoryNamer("FileName") = info.Name

the error is

'DirectoryNamer' is not a member of 'System.IO.FileInfo'

PLEASE REPLY AS TO WHAT TO DO IN THIS REGARD....

THANKS AGAIN...

 

 

0
ramkunchur
6/11/2008 5:47:35 AM

hi manish...

i solved the problem

the line given by you was

r("Folder") = info.DirectoryNamer("FileName") = info.Name

but what actually u wanted to say was:

r("Folder") = info.DirectoryName

r("FileName") = info.Name

by mistake you have pasted both lines in a single line i guess...

It works perfectly now....

Thanks to you

I am marking your reply as Answer

THANKS AGAIN....

0
ramkunchur
6/11/2008 6:16:42 AM
ramkunchur:

hey johram....

There is no such line as

<asp:GridView AutoGenerateColumns="False" ... >

in my aspx....

What to do?

And I want to display only Name & LastAccessTime and not Path and Length....

Please reply....

Thanks

You can find the AutoGenerateColumn if you click the gridview an arrow will apear on the upper right corner of the gridview. Click the arrow then click edit Columns, at the lower part of the menu there is a checkbox that says "Auto-Generate Fields" Uncheck it. You can also set each column visibility and other properties. You can set visibilty of a column which you dont want the users to see.
0
Stormbind
6/11/2008 7:39:14 AM

To sum it up, there are two approaches in this case:

1) Use AutoGenerateColumns="True" (the default behavior). This will display all columns available in the datasource. If you use this setting, you need to copy only the columns you want from the file list and put it in e.g. a DataTable.

2) Use AutoGenerateColumns="False". This will allow you to specify explicitly in the GridView which columns to display. The benefit from this approach is that you can bind to a richer source (i.e. containing more columns) without having to adopt the source.

So with the first approach, you modify the source before displaying it and in the second approach you keep the source but modify the display.


If this post was useful to you, please mark it as answer. Thank you!
0
johram
6/11/2008 9:02:16 AM
Reply:

Similar Artilces:

How to get the string array that starts with prefixtext
 Helloo, i am using a web service to autocomplete a textbox The database contains a keywords column ..each colum contains more than 1 keywords  LIKE "INDIA WORLD IRAQ" So i need to use RegEx to split each keywords.But How can i extract only strings that starts with the prefixtext into an array??Please HelppI hav put my code below   1 public string[] GetKeywords(string prefixText, int count) 2 { 3 // int count = 10; 4 string connString = ConfigurationManager.ConnectionStrings["dnas_newConnectionString...

Getting error while converting string to double: Input string was not in correct format
Select Case LocalMeasuringUnitText Case "Currency" 'do the conversion hereDim ConversionRate As Double = GetConversionRate(_LanguageID)   Dim UKValue As Double 'String.Format("{0:c}", SelectedRow(rowloop).Item("TransData").ToString()) Dim varValue As Object = NothingDim Stringvalue As Object = SelectedRow(rowloop).Item("TransData").ToString.Trim 'varValue = Double.TryParse(Stringvalue, varValue) 'CType(Stringvalue, System.Double) 'UKValue = Convert.ToDouble(Stringvalue) / GetConversionRate(ConfigurationManager.AppS...

Getting ORA-06502 string to integer conversion error, but no string is involved in parameter in a call on a datasnap sqlStoredProc
I was suddenly getting strange conversion errors when calling a stored procedure in a Oracle server (11g) The package routine(s) compile ok, and call parameters are 2 integer fields, a timestamp and an integer out (id of actual record) After compiling the package in Oracle server, I update Datasnap server by changing all procedure names and back again in all tSQLStoredProcedure components put on the ServerMethods tDSServerModule, I recompile (having service stopped) and restart service, open client and in tsqlconnection I make a new proxy so correct parameters are set (after...

trying to get started and i am getting this error
when i go to http://www.porkchopsplayground.com, i get: DotNetNuke Upgrade Error The Assembly Version ( [ASSEMBLYVERSION] ) does not match the Database Version ( [DATABASEVERSION] ) ERROR: Could not connect to database. Could not find file 'd:\hosting\nmoran26\Providers\DataProviders\AccessDataProvider\DotNetNuke.mdb'. Any suggestions will be appreciated. Thanks, Nicole Do you have a username and password set on your database? Make sure you follow the steps mentionned in the Readme.txt located in the documentation folder. In any case make sure your credentials for yo...

get Format of the initialization string does not conform to specification starting at index 0. error
Hi, I have a page in which I have the following line in VB, my "abcConnectionString" is set in the web.config file. But when I click on the button, I get this error: Format of the initialization string does not conform to specification starting at index 0. What should I do? thank you.Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim txt1 As TextBox = Me.FindControl("TextBox1") ' txt1.Text = "i will start"Dim myConnection As New SqlConnection("abcConnectionString") myConnection.Open()D...

hi , i have a littel problem with arrays, i want use with replace function of string and i get a error
hi in php its worked well, but when i try to convert it to asp.net i get this error i try to replace all the characters in field that in array aa with the characters that in abstring[] ab = new string[] { "5", "4", "3", "2", "1" }; string[] aa = new string[] { "a", "b", "c", "d", "e" }; string field = "abcdabcs"; Response.Write(field.Replace(ab, aa).ToString()); the result will need to be : ------------------------------------------------------ 54325432 --------------------...

superreview cancelled: [Bug 211625] Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk : [Attachment 127564] Update Desktop Get Info string to 1.5b
Matti (Matthias "hating marquee" Versen) <matti@mversen.de> has cancelled lpham@netscape.com's request for superreview: Bug 211625: Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk http://bugzilla.mozilla.org/show_bug.cgi?id=211625 Attachment 127564: Update Desktop Get Info string to 1.5b http://bugzilla.mozilla.org/attachment.cgi?id=127564&action=edit ------- Additional Comments from Matti (Matthias "hating marquee" Versen) <matti@mversen.de> obsolete review request ...

superreview requested: [Bug 211625] Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk : [Attachment 127564] Update Desktop Get Info string to 1.5b
<lpham@netscape.com> has asked Yumaris Calonje <ycalonje@netscape.com> for superreview: Bug 211625: Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk http://bugzilla.mozilla.org/show_bug.cgi?id=211625 Attachment 127564: Update Desktop Get Info string to 1.5b http://bugzilla.mozilla.org/attachment.cgi?id=127564&action=edit ...

superreview requested: [Bug 211625] Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk : [Attachment 127588] Update Mac Desktop get info string to 1.5b
<lpham@netscape.com> has asked Yumaris Calonje <ycalonje@netscape.com> for superreview: Bug 211625: Update Mac Desktop Get Info string to Mozilla 1.5b on the trunk http://bugzilla.mozilla.org/show_bug.cgi?id=211625 Attachment 127588: Update Mac Desktop get info string to 1.5b http://bugzilla.mozilla.org/attachment.cgi?id=127588&action=edit ------- Additional Comments from <lpham@netscape.com> >Index: Info.plist >=================================================================== >RCS file: /cvsroot/mozilla/xpfe/bootstrap/macbuild/Contents/Info.pl...

Getting error in Net::SFTP with get function
------=_Part_7028_3315294.1193837808284 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi All, I have the following code as part of my program; print "---=========> $file, $localFile\n"; $sftp -> get( $file, $localFile ) || warn("errrrr0rrrrr _---> $!".$sftp->status."\n");^M Even though it has downloaded the file properly, it is giving the following message: ---=========> /trading/tiscrdenhlist10310000.txt.old, /export/home/crdadm/rajeev/tiscrdenhlist103...

String Manipulation
 Hello all, Using VB I'm trying to have a multiline textbox that a user will put in a quantity and a name as follows: 3xApple2xPear4xOrangeAnd when they click a button I want each part of this as a separate value, so far I have the following: Function GetSingleCards(ByVal AllFruits As String) As String Dim OurFruits As String() = Nothing Dim SingleFruit As String Dim ReturnThis As String OurFruit = AllFruits.Split(vbCrLf) For Each SingleFruit In OurFruits ReturnThis &= SingleFruit & ", " '...

VS.NET 2005 is ignoring in web.config strict="true". I get no error when I try this: Dim x As Integer = "string"
Hello,I have this in my VS.NET 2005 web.config <compilation debug="true" strict="true" explicit="true">When I do this in my vb code:Dim x As Integer = "string"I get no error. When I hit compilation I also get no error. What am I doing wrong?Thanks for helping!Regards,J. Bauer It's a bug of some sort See this response by Scott Guthriehttp://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=3c1c9898-8076-4f69-a5e2-e99573d03c6e Unfortunately we don’t have a GUI based way to configure this. L It is something we will make sure gets added back in, though, with the next...

Getting all text at start of a string
Hello,I have a string (from a weather feed) that looks like:Monday: Mainly Sunny, 25.5°C Is it possible to get everything before the :So I can just get the day, and not the conditionsThe idea is that the feed looks likeMonday: asdsfasfMonday Night: asdsfasfTuesday: AFASFetc,Thanks  Try this: string s = "Monday: Mainly Sunny, 25.5°C"; string d = s.Split(':')[0];Thanks, EdMicrosoft MVP - ASP/ASP.NET...

Getting string array from SQL?
I'm playing around with a User/Role system. I currently have a function to retrieve a user which works fine, now I want a function to retrieve a user's assigned roles from the database as well. I have the stored procedure needed and the basic code logic to retrieve the roles as a DataSet or a SqlDataReader. The problem is that I need the roles as an array of strings to assign to my GenericPrinciple object. So; How do I retrieve the data and make it an array? Or is there another, better way to accomplish this? It might be more convenient to adjust the GenericPrinciple object to also ...

Web resources about - How to copy strings in array of strings....I am getting some errors.... - asp.net.getting-started

Kubo and the Two Strings - Wikipedia, the free encyclopedia
Kubo and the Two Strings is an upcoming American 3D stop motion film produced by Laika for Focus Features . It is being directed by Travis Knight ...

Facebook + Twitter + Klout + Pinterest = No-Strings-Attached Dates? April Fool’s!
... Twitter, and Klout, and then brings it into Pinterest and uses a “secret algorithm” to match up “like-minded Pinterest users” for “no-strings ...

Query Strings - Quora
Quora is your best source for knowledge.

UltraTuner - Ultra Precise Chromatic Tuner for Guitar, Bass, Strings, Brass and More on the App Store ...
Get UltraTuner - Ultra Precise Chromatic Tuner for Guitar, Bass, Strings, Brass and More on the App Store. See screenshots and ratings, and read ...

Kubo and the Two Strings Trailer 2016 - YouTube
Kubo and the Two Strings Trailer 2016. Kubo lives a quiet, normal life in a small shoreside village until a spirit from the past turns his life ...

Pakistani band Strings battles it out with Indian band Euphoria at Red Bull Soundclash - The National ...
Everyone's a winner at battle of the bands as musicians from both bands declare a draw, delighting the crowd at Dubai World Trade Centre.

Home help has strings attached
Home help has strings attached

A bad time for households to tighten the purse strings
Growth continues to be driven largely by resource exports, leaving the economy vulnerable to the whims of China. Household consumption is needed ...

Pure strings
Pure strings


Resources last updated: 2/12/2016 3:52:49 AM