Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c# - Putting a .txt file into a DataGridView

I have an openFileButton that, when clicked, will open a file that looks like this:

RefDeg  Part#       Xcntr    Ycntr    Rot  PkgStyle  
U6      IC-00279G   33.411   191.494  0    QFP32     
U1      IC-00272G   38.011   200.644  90   BGA177    
U5      IC-00273G   46.311   179.494  0    QFP40     
R54     EXCLUDES    36.411   173.694  0    0402_2    
R71     EXCLUDES    38.236   186.994  0    0402_2    
R39     EXCLUDES    38.861   188.544  90   0402_2    
C23     CAP-00130G  37.911   178.854  90   0402_3    
C88     CAP-00010G  52.036   179.019  0    0603_4    
C89     CAP-00010G  43.561   173.744  90   0603_3    
X1      XTL-00013G  49.211   204.819  0    Crystal   
X2      XTL-00012G  53.061   183.469  0    Crystal   
D1      LED-00011G  58.611   181.394  0    LED       
U10     IC-00198G   56.661   205.744  0    SOT       
        IC-00173G   59.911   205.744  0    SOT23-5   
U2      IC-00274G   51.786   199.044  0    VFBGA     
Q1      Excludes    43.147   189.769  0    MOSFET    
U4      IC-00167G   59.211   177.394  0    SOT235_2  
FID1    FIDUCIAL    5.080    24.130   0    FIDUCIAL  
        FIDUCIAL    59.586   192.944  0    FIDUCIAL  

When the file is selected and opened I would like to put/import the .txt files line into a DataGridView and then each column into a new column on that same line in the DataGridView.

Does anyone know a quick short way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could split the lines and loop all rows/columns to generate the DataTable:

var fileName = this.OpenFileDialog1.FileName;
var rows = System.IO.File.ReadAllLines(fileName);
Char[] separator = new Char [] {' '};
DataTable tbl = new DataTable(fileName);
if (rows.Length != 0) {
    foreach (string headerCol in rows(0).Split(separator)) {
        tbl.Columns.Add(new DataColumn(headerCol));
    }
    if (rows.Length > 1) {
        for (rowIndex = 1; rowIndex < rows.Length; rowIndex++) {
            var newRow = tbl.NewRow();
            var cols = rows(rowIndex).Split(separator);
            for (colIndex = 0; colIndex < cols.Length; colIndex++) {
                newRow(colIndex) = cols(colIndex);
            }
            tbl.Rows.Add(newRow);
        }
    }
}

Then use this DataTable as DataSource for your DataGridView.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...