1

现在我正在使用以下代码填充 DataGridView 中的第三列:

 Bitmap img = new   
 Bitmap(@"C:\Project\Images\Image1.jpg");
 DataGridView [2, 0].Value = img;           //2,0 is 1st row, 3rd column

 Bitmap img2 = new   
 Bitmap(@"C:\Project\Images\Image2.jpg");
 DataGridView [2, 1].Value = img2;           //2,1 is 2nd row, 3rd column

第三列正确填充了图像,但我将此代码重复了 26 次。为简单起见,我只想知道它们是否是一种更简单的方法,例如制作数组或将图像直接插入我的数据库。如果这是一个新手问题,我深表歉意,因为我对 C# 比较陌生。

谢谢!

4

4 回答 4

2

我建议使用Directory.GetFiles(path);which 为您提供目录中所有文件的数组。使用它,您不必担心文件的名称是 image1,image2,..

string path = @"C:\Project\Images\";
            string[] arr =  Directory.GetFiles(path);
            for (int i = 0 ; i < arr.Length ; i++)
            {
                Bitmap img = new Bitmap(Path.Combine(path , arr[i]));
                DataGridView [2, i].Value = img;
            }
于 2012-11-19T05:15:35.200 回答
1

就像是:

int numberOfImages = 10; // Replace 10 with number of your images
for(int i=0; i<numberOfImages; i++)
{
   using(Bitmap img = new Bitmap(string.Format(@"C:\Project\Images\Image{0}.jpg", i+1)))
   {
       DataGridView [2, i].Value = img;
   }    
}
于 2012-11-19T05:14:26.217 回答
0

您需要学习循环/迭代的概念。查看有关迭代语句的文章,例如forforeach

 for (int i = 0; i < 26; i++)
 {
     DataGridView [i, 1].Value = 
        new Bitmap(String.Format(@"C:\Project\Images\Image{0}.jpg", i));
 }
于 2012-11-19T05:15:54.343 回答
0

试试这个

ASPX Gridview 代码

<asp:GridView ID="grdImages" runat="server" BorderStyle="None" GridLines="None"
        ShowHeader="false" AutoGenerateColumns="False" Width="240">
        <Columns>
            <asp:ImageField DataImageUrlField="FileName"></asp:ImageField>
        </Columns>
</asp:GridView>

cs代码

 protected void Page_Load(object sender, EventArgs e)
    {
        string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Images\Temple";
        // string path = @"D:\Blog\ImageShow\Images"; // This statement also valid

        string[] extensions = { "*.jpg", "*.png", "*.bmp" };

        List<string> files = new List<string>();
        foreach (string filter in extensions)
        {
            files.AddRange(System.IO.Directory.GetFiles(path, filter));
        }

        IList<ImageFileInfo> imageFileList = new List<ImageFileInfo>();
        foreach (string strFileName in files)
        {
            // Change the Absolute path to relative path of File Name and add to the List
            imageFileList.Add(new ImageFileInfo { FileName = ResolveUrl(strFileName.Replace(Server.MapPath("/"), "~/")) });
        }
        grdImages.DataSource = imageFileList;
        grdImages.DataBind();
    }
于 2012-11-19T05:21:38.577 回答