C#winform中ListView的使用

使用ListView模仿Windows系统的资源管理器界面,实现文件(夹)的浏览、重命名、删除及查询等功能,主要功能界面展示如下:

C#winform中ListView的使用

C#winform中ListView的使用

1.MainForm.cs及MainForm.Designer.cs

C#winform中ListView的使用
  1 using System;

  2 using System.Collections.Generic;

  3 using System.ComponentModel;

  4 using System.Data;

  5 using System.Drawing;

  6 using System.Linq;

  7 using System.Text;

  8 using System.Windows.Forms;

  9 using System.IO;

 10 

 11 namespace Controls

 12 {

 13     public partial class MainForm : Form

 14     {

 15         #region 成员变量

 16         /// <summary>

 17         /// 用于递归计算文件夹大小

 18         /// </summary>

 19         private long folderSize = 0;

 20 

 21         /// <summary>

 22         ///打开文件夹根路径

 23         /// </summary>

 24         private string rootPath = string.Empty;

 25         #endregion

 26 

 27         #region 初期化

 28         /// <summary>

 29         /// 默认构造函数

 30         /// </summary>

 31         public MainForm()

 32         {

 33             InitializeComponent();

 34             //给窗体注册键盘事件

 35             this.KeyPreview = true;

 36         }

 37 

 38         /// <summary>

 39         /// 初始化窗体,绑定事件

 40         /// </summary>

 41         /// <param name="sender"></param>

 42         /// <param name="e"></param>

 43         private void MainForm_Load(object sender, EventArgs e)

 44         {

 45             this.大图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);

 46             this.详细信息ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);

 47             this.平铺ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);

 48             this.小图标ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);

 49             this.列表ToolStripMenuItem.Click += new System.EventHandler(this.ToolStripMenuItem_Click);

 50         }

 51         #endregion

 52 

 53         #region 事件处理

 54         /// <summary>

 55         /// 搜索框符合条件的文件夹或文件

 56         /// </summary>

 57         /// <param name="sender"></param>

 58         /// <param name="e"></param>

 59         private void btnSearch_Click(object sender, EventArgs e)

 60         {

 61             AddItemsToListView(txtPath.Text, txtSearch.Text.Trim());

 62             AddHeaderToListView(this.lvwData);

 63         }

 64 

 65         /// <summary>

 66         /// 给搜索框添加Enter快捷键

 67         /// </summary>

 68         /// <param name="sender"></param>

 69         /// <param name="e"></param>

 70         private void MainForm_KeyDown(object sender, KeyEventArgs e)

 71         {

 72             //搜索框获得焦点且按下Enter键时,执行搜索

 73             if (txtSearch.Focused && e.KeyCode == Keys.Enter)

 74             {

 75                 this.btnSearch_Click(sender, e);

 76             }

 77         }

 78 

 79         /// <summary>

 80         /// 返回上级目录

 81         /// </summary>

 82         /// <param name="sender"></param>

 83         /// <param name="e"></param>

 84         private void btnUp_Click(object sender, EventArgs e)

 85         {

 86             if (txtPath.Text == rootPath || !txtPath.Text.Contains("\\"))

 87             {

 88                 return;

 89             }

 90             //找到文件夹上级目录的绝对路径

 91             txtPath.Text = txtPath.Text.Substring(0, txtPath.Text.LastIndexOf("\\"));

 92             AddItemsToListView(txtPath.Text);

 93             AddHeaderToListView(this.lvwData);

 94         }

 95 

 96         /// <summary>

 97         /// 打开文件夹,显示文件夹

 98         /// </summary>

 99         /// <param name="sender"></param>

100         /// <param name="e"></param>

101         private void btnFolder_Click(object sender, EventArgs e)

102         {

103             DialogResult dr = fbdData.ShowDialog();

104             string path = fbdData.SelectedPath.ToString();

105             if (dr == DialogResult.OK && path != "")

106             {

107                 rootPath = path;

108                 txtPath.Text = path;

109             }

110         }

111 

112         /// <summary>

113         /// 新建文件夹,选中文件夹

114         /// </summary>

115         /// <param name="sender"></param>

116         /// <param name="e"></param>

117         private void btnAdd_Click(object sender, EventArgs e)

118         {

119             string fullpath = string.Empty;

120             AddForm addForm = new AddForm(btnAdd.Text);

121             addForm.ShowDialog();

122             if (addForm.ButtonFlag)

123             {

124                 fullpath = txtPath.Text + "\\" + addForm.TxtName;

125             }

126             else

127             {

128                 return; //排除关闭窗口异常

129             }

130             try

131             {

132                 if (Directory.Exists(fullpath))

133                 {

134                     MessageBox.Show("该文件名已经存在!", "提示");

135                     return;

136                 }

137                 Directory.CreateDirectory(fullpath);

138                 AddItemsToListView(txtPath.Text);

139                 AddHeaderToListView(this.lvwData);

140             }

141             catch (NullReferenceException ex)

142             {

143                 MessageBox.Show(ex.Message, "提示");

144             }

145             finally

146             {

147                 //选中新增的项,并显示在视野范围内

148                 for (int i = 0; i < lvwData.Items.Count; i++)

149                 {

150                     if (lvwData.Items[i].Tag.ToString() == fullpath)

151                     {

152                         //先设置ListView选中

153                         lvwData.Focus();

154                         lvwData.Items[i].Selected = true;

155                         //在视野范围内显示

156                         lvwData.EnsureVisible(i);

157                         break;

158                     }

159                 }

160             }

161         }

162 

163         /// <summary>

164         /// 重命名文件夹

165         /// </summary>

166         /// <param name="sender"></param>

167         /// <param name="e"></param>

168         private void btnRename_Click(object sender, EventArgs e)

169         {

170             if (lvwData.SelectedItems.Count <= 0)

171             {

172                 return;

173             }

174             string fullName = lvwData.SelectedItems[0].Tag.ToString();

175             string path = fullName.Substring(0, fullName.LastIndexOf("\\") + 1);//文件路径

176             string suffix = GetSuffixName(fullName);//后缀名

177             //文件名或文件夹名

178             string fileName = string.Empty;

179             if (suffix != string.Empty)

180             {

181                 fileName = fullName.Substring(fullName.LastIndexOf("\\") + 1,

182                         fullName.LastIndexOf(".") - fullName.LastIndexOf("\\") - 1);//文件名

183             }

184             else

185             {

186                 fileName = fullName.Substring(fullName.LastIndexOf("\\") + 1);//文件夹名

187             }

188             string fullPath = string.Empty;

189             AddForm addForm = new AddForm(btnRename.Text, fileName);

190             addForm.ShowDialog();

191             if (suffix != string.Empty)

192             {

193                 fullPath = path + addForm.TxtName + "." + suffix;

194             }

195             else

196             {

197                 fullPath = path + addForm.TxtName;

198             }

199             //直接关闭窗口时

200             if (!addForm.ButtonFlag)

201             {

202                 return;

203             }

204             try

205             {

206                 //重命名文件夹

207                 if (suffix == string.Empty)

208                 {

209                     if (Directory.Exists(fullPath))

210                     {

211                         MessageBox.Show("该文件名已经存在!", "提示");

212                         return;

213                     }

214                     Directory.Move(fullName, fullPath);

215                 }

216                 //重命名文件

217                 else

218                 {

219                     if (File.Exists(fullPath))

220                     {

221                         MessageBox.Show("该文件名已经存在!", "提示");

222                         return;

223                     }

224                     File.Move(fullName, fullPath);

225                 }

226                 AddItemsToListView(txtPath.Text);

227                 AddHeaderToListView(this.lvwData);

228             }

229             catch (NullReferenceException ex)

230             {

231                 MessageBox.Show(ex.Message);

232             }

233         }

234 

235         /// <summary>

236         /// 删除文件夹

237         /// </summary>

238         /// <param name="sender"></param>

239         /// <param name="e"></param>

240         private void btnDelete_Click(object sender, EventArgs e)

241         {

242             int count = lvwData.SelectedItems.Count;

243             if (count <= 0)

244             {

245                 return;

246             }

247             DialogResult result = MessageBox.Show("你确定删除这" + count + "项吗?", "提示",

248                                     MessageBoxButtons.YesNo, MessageBoxIcon.Question);

249             if (result == DialogResult.Yes)

250             {

251                 string path;

252                 ListViewItem selectitem;

253                 for (int i = 0; i < lvwData.SelectedItems.Count; ) //此处不能i++

254                 {

255                     selectitem = lvwData.SelectedItems[i];

256                     path = selectitem.Tag.ToString();

257                     lvwData.Items.Remove(selectitem);

258                     if (File.Exists(path))

259                     {

260                         File.Delete(path);

261                     }

262                     else if (Directory.Exists(path))

263                     {

264                         Directory.Delete(path, true);

265                     }

266                     lvwData.Update();

267                 }

268             }

269         }

270 

271         /// <summary>

272         /// List选中项时发生

273         /// </summary>

274         /// <param name="sender"></param>

275         /// <param name="e"></param>

276         private void lvwData_ItemActivate(object sender, EventArgs e)

277         {

278             ListView lv = (ListView)sender;

279             if (lv.SelectedItems.Count <= 0)

280             {

281                 return;

282             }

283             string filename = lv.SelectedItems[0].Tag.ToString();

284             //如果是文件夹,就打开它

285             if (Directory.Exists(filename))

286             {

287                 AddItemsToListView(filename);

288                 AddHeaderToListView(this.lvwData);

289                 //获取打开的文件夹路径

290                 txtPath.Text = filename;

291             }

292             //如果是文件,就执行它

293             else

294             {

295                 System.Diagnostics.Process.Start(filename);

296             }

297         }

298 

299         /// <summary>

300         /// 根据路径,获取ListView中的显示项

301         /// </summary>

302         /// <param name="sender"></param>

303         /// <param name="e"></param>

304         private void txtPath_TextChanged(object sender, EventArgs e)

305         {

306             AddItemsToListView(txtPath.Text);

307             AddHeaderToListView(this.lvwData);

308         }

309 

310         /// <summary>

311         /// ListView列表显示样式

312         /// </summary>

313         /// <param name="sender"></param>

314         /// <param name="e"></param>

315         private void ToolStripMenuItem_Click(object sender, EventArgs e)

316         {

317             ToolStripMenuItem tsMenumItem = sender as ToolStripMenuItem;

318             if (tsMenumItem.Checked)

319             {

320                 return;//已经选中则返回

321             }

322             else

323             {

324                 //清除勾选的右键菜单项

325                 ClearCheckState(cmsStyle);

326                 //勾选选中的右键菜单项

327                 tsMenumItem.Checked = true;

328             }

329             switch (tsMenumItem.Text)

330             {

331                 case "大图标":

332                     lvwData.View = View.LargeIcon;

333                     break;

334                 case "详细信息":

335                     lvwData.View = View.Details;

336                     break;

337                 case "小图标":

338                     lvwData.View = View.SmallIcon;

339                     break;

340                 case "列表":

341                     lvwData.View = View.List;

342                     break;

343                 case "平铺":

344                     lvwData.View = View.Tile;

345                     break;

346             }

347         }

348 

349         /// <summary>

350         /// 清除勾选的右键菜单项

351         /// </summary>

352         /// <param name="cms">右键菜单</param>

353         /// <param name="clearAll">是否全部清除</param>

354         private void ClearCheckState(ContextMenuStrip cms, bool clearAll = false)

355         {

356             ToolStripMenuItem tsMenumItemTemp;

357             for (int i = 0; i < cms.Items.Count; i++)

358             {

359                 if (!(cms.Items[i] is ToolStripMenuItem))

360                 {

361                     continue;

362                 }

363                 tsMenumItemTemp = cms.Items[i] as ToolStripMenuItem;

364                 if (tsMenumItemTemp.Checked)

365                 {

366                     tsMenumItemTemp.Checked = false;

367                     if (!clearAll)

368                     {

369                         break;

370                     }

371                 }

372             }

373         }

374         #endregion

375 

376         #region 设置ListView的显示项

377         /// <summary>

378         /// 根据根节点类型,设置listview显示项

379         /// </summary>

380         /// <param name="root">根节点</param>

381         /// <param name="keywords">搜索关键字</param>

382         private void AddItemsToListView(string root, string keywords = "")

383         {

384             //把当前ListView里的所有选项与所有列名都删除

385             lvwData.Clear();

386             lvwData.BeginUpdate();

387             //根节点是文件

388             if (File.Exists(root))

389             {

390                 AddFileToListView(new FileInfo(root), keywords);

391             }

392             //根节点是文件夹

393             else

394             {

395                 DirectoryInfo dir = new DirectoryInfo(root);

396                 DirectoryInfo[] dirs = dir.GetDirectories();

397                 FileInfo[] files = dir.GetFiles();

398                 //把子文件夹信息添加到ListView中显示

399                 foreach (DirectoryInfo directoryInfo in dirs)

400                 {

401                     AddFolderToListView(directoryInfo, keywords);

402                 }

403                 //把文件夹下文件信息添加到ListView中显示

404                 foreach (FileInfo fileInfo in files)

405                 {

406                     AddFileToListView(fileInfo, keywords);

407                 }

408             }

409             this.lvwData.EndUpdate();

410         }

411 

412         /// <summary>

413         /// 将文件添加到ListView中显示

414         /// </summary>

415         /// <param name="fileInfo">文件全路径</param>

416         /// <param name="keywords">搜索关键字</param>

417         private void AddFileToListView(FileInfo fileInfo, string keywords)

418         {

419             ListViewItem lvi = new ListViewItem();//文件项

420             lvi.Tag = fileInfo.FullName;

421             lvi.Text = fileInfo.Name;

422             lvi.ImageIndex = imgLarge.Images.Count - 1;

423             if (keywords != "" && (!lvi.Text.Contains(keywords)))

424             {

425                 return;//搜索不到关键字,不将文件添加到ListView中显示

426             }

427             //文件的名称属性项

428             lvi.SubItems[0].Tag = lvi.Tag;

429             lvi.SubItems[0].Text = lvi.Text;

430             //文件大小属性项

431             ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();

432             lvsi.Tag = fileInfo.Length;

433             lvsi.Text = FormatFolderSize(fileInfo.Length);

434             lvi.SubItems.Add(lvsi);

435             //修改日期属性项

436             lvsi = new ListViewItem.ListViewSubItem();

437             lvsi.Tag = fileInfo.LastAccessTime.ToString();

438             lvsi.Text = fileInfo.LastAccessTime.ToString();

439             lvi.SubItems.Add(lvsi);

440             //添加文件

441             this.lvwData.Items.Add(lvi);

442         }

443 

444         /// <summary>

445         /// 将文件夹添加到ListView中显示

446         /// </summary>

447         /// <param name="DirectoryInfo">文件夹</param>

448         /// <param name="keywords">搜索关键字</param>

449         private void AddFolderToListView(DirectoryInfo DirectoryInfo, string keywords)

450         {

451             ListViewItem lvi = new ListViewItem();

452             lvi.Tag = DirectoryInfo.FullName;

453             lvi.Text = DirectoryInfo.Name;//显示名称

454             lvi.ImageIndex = 0;

455             if (keywords != "" && (!lvi.Text.Contains(keywords)))

456             {

457                 return;//搜索不到关键字,不将文件夹添加到ListView中显示

458             }

459             // 文件夹的名称属性项

460             lvi.SubItems[0].Tag = lvi.Tag;

461             lvi.SubItems[0].Text = lvi.Text;

462             //文件夹大小属性项

463             ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();

464             lvsi.Tag = GetFolderSize(DirectoryInfo);

465             lvsi.Text = FormatFolderSize(folderSize);

466             folderSize = 0;//清零计算文件夹大小的变量

467             lvi.SubItems.Add(lvsi);

468             //修改日期属性项

469             lvsi = new ListViewItem.ListViewSubItem();

470             lvsi.Tag = DirectoryInfo.LastAccessTime.ToString();

471             lvsi.Text = DirectoryInfo.LastAccessTime.ToString();

472             lvi.SubItems.Add(lvsi);

473             //添加文件夹

474             this.lvwData.Items.Add(lvi);

475         }

476 

477         /// <summary>

478         /// 递归计算文件夹的大小

479         /// </summary>

480         /// <param name="DirectoryInfo">文件夹</param>

481         /// <returns>文件夹大小</returns>

482         private long GetFolderSize(DirectoryInfo DirectoryInfo)

483         {

484             DirectoryInfo[] dirs = DirectoryInfo.GetDirectories();

485             FileInfo[] files = DirectoryInfo.GetFiles();

486             //是文件夹时,继续递归

487             if (dirs.Length > 0)

488             {

489                 foreach (DirectoryInfo dir in dirs)

490                 {

491                     GetFolderSize(dir);

492                 }

493             }

494             //是文件时,进行累加计算

495             foreach (FileInfo fi in files)

496             {

497                 folderSize = folderSize + fi.Length;

498             }

499             return folderSize;

500         }

501 

502         /// <summary>

503         /// 将文件夹大小转化为直观的文字显示

504         /// </summary>

505         /// <param name="size">文件夹大小</param>

506         /// <returns>文件夹大小的文字表示</returns>

507         private string FormatFolderSize(long size)

508         {

509             if ((size >> 30) > 0)

510             {

511                 //保留两位小数

512                 return ((size >> 20) / 1024.0).ToString("F2") + " GB";

513             }

514             else if ((size >> 20) > 0)

515             {

516                 //保留两位小数

517                 return ((size >> 10) / 1024.0).ToString("F2") + " MB";

518             }

519             else

520             {

521                 return (size >> 10) + " KB";

522             }

523         }

524 

525         /// <summary>

526         /// 为listview添加列标题

527         /// </summary>

528         private void AddHeaderToListView(ListView listView)

529         {

530             ColumnHeader ch = new ColumnHeader();

531             ch.Text = "文件名";

532             ch.Width = 150;

533             listView.Columns.Add(ch);

534 

535             ch = new ColumnHeader();

536             ch.Width = 70;

537             ch.Text = "大小";

538             listView.Columns.Add(ch);

539 

540             ch = new ColumnHeader();

541             ch.Text = "修改日期";

542             ch.Width = 140;

543             listView.Columns.Add(ch);

544         }

545         #endregion

546 

547         #region 经常使用的公共方法

548         /// <summary>

549         /// 获取文件后缀名(小写)

550         /// </summary>

551         /// <param name="path">文件全路径或文件名</param>

552         public string GetSuffixName(string path)

553         {

554             string suffix = string.Empty;

555             if (path.Contains("."))

556             {

557                 suffix = path.Substring(path.LastIndexOf(".") + 1);//后缀名

558             }

559             return suffix.ToLower();

560         }

561 

562         /// <summary>

563         /// 获取应用程序根路径

564         /// </summary>

565         public string GetApplicationPath()

566         {

567             string path = Application.StartupPath;

568             string folderName = String.Empty;

569             while (folderName.ToLower() != "bin")

570             {

571                 path = path.Substring(0, path.LastIndexOf("\\"));

572                 folderName = path.Substring(path.LastIndexOf("\\") + 1);

573             }

574             return path.Substring(0, path.LastIndexOf("\\") + 1);

575         }

576         #endregion

577     }

578 }
View Code
C#winform中ListView的使用
  1 namespace Controls

  2 {

  3     partial class MainForm

  4     {

  5         /// <summary>

  6         /// 必需的设计器变量。

  7         /// </summary>

  8         private System.ComponentModel.IContainer components = null;

  9 

 10         /// <summary>

 11         /// 清理所有正在使用的资源。

 12         /// </summary>

 13         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>

 14         protected override void Dispose(bool disposing)

 15         {

 16             if (disposing && (components != null))

 17             {

 18                 components.Dispose();

 19             }

 20             base.Dispose(disposing);

 21         }

 22 

 23         #region Windows 窗体设计器生成的代码

 24 

 25         /// <summary>

 26         /// 设计器支持所需的方法 - 不要

 27         /// 使用代码编辑器修改此方法的内容。

 28         /// </summary>

 29         private void InitializeComponent()

 30         {

 31             this.components = new System.ComponentModel.Container();

 32             System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));

 33             this.lvwData = new System.Windows.Forms.ListView();

 34             this.imgLarge = new System.Windows.Forms.ImageList(this.components);

 35             this.imgSmall = new System.Windows.Forms.ImageList(this.components);

 36             this.btnDelete = new System.Windows.Forms.Button();

 37             this.btnFolder = new System.Windows.Forms.Button();

 38             this.btnRename = new System.Windows.Forms.Button();

 39             this.txtPath = new System.Windows.Forms.TextBox();

 40             this.txtSearch = new System.Windows.Forms.TextBox();

 41             this.btnUp = new System.Windows.Forms.Button();

 42             this.btnAdd = new System.Windows.Forms.Button();

 43             this.fbdData = new System.Windows.Forms.FolderBrowserDialog();

 44             this.cmsStyle = new System.Windows.Forms.ContextMenuStrip(this.components);

 45             this.大图标ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

 46             this.详细信息ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

 47             this.平铺ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

 48             this.小图标ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

 49             this.列表ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

 50             this.cmsStyle.SuspendLayout();

 51             this.SuspendLayout();

 52             // 

 53             // lvwData

 54             // 

 55             this.lvwData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

 56                         | System.Windows.Forms.AnchorStyles.Left)

 57                         | System.Windows.Forms.AnchorStyles.Right)));

 58             this.lvwData.ContextMenuStrip = this.cmsStyle;

 59             this.lvwData.LargeImageList = this.imgLarge;

 60             this.lvwData.Location = new System.Drawing.Point(12, 45);

 61             this.lvwData.Name = "lvwData";

 62             this.lvwData.Size = new System.Drawing.Size(530, 334);

 63             this.lvwData.SmallImageList = this.imgSmall;

 64             this.lvwData.TabIndex = 4;

 65             this.lvwData.UseCompatibleStateImageBehavior = false;

 66             this.lvwData.ItemActivate += new System.EventHandler(this.lvwData_ItemActivate);

 67             // 

 68             // imgLarge

 69             // 

 70             this.imgLarge.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgLarge.ImageStream")));

 71             this.imgLarge.TransparentColor = System.Drawing.Color.Transparent;

 72             this.imgLarge.Images.SetKeyName(0, "folder.png");

 73             this.imgLarge.Images.SetKeyName(1, "file.png");

 74             // 

 75             // imgSmall

 76             // 

 77             this.imgSmall.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgSmall.ImageStream")));

 78             this.imgSmall.TransparentColor = System.Drawing.Color.Transparent;

 79             this.imgSmall.Images.SetKeyName(0, "folder.png");

 80             this.imgSmall.Images.SetKeyName(1, "file.png");

 81             // 

 82             // btnDelete

 83             // 

 84             this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));

 85             this.btnDelete.Location = new System.Drawing.Point(466, 393);

 86             this.btnDelete.Name = "btnDelete";

 87             this.btnDelete.Size = new System.Drawing.Size(75, 23);

 88             this.btnDelete.TabIndex = 8;

 89             this.btnDelete.Text = "删除文件";

 90             this.btnDelete.UseVisualStyleBackColor = true;

 91             this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);

 92             // 

 93             // btnFolder

 94             // 

 95             this.btnFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

 96             this.btnFolder.Location = new System.Drawing.Point(12, 393);

 97             this.btnFolder.Name = "btnFolder";

 98             this.btnFolder.Size = new System.Drawing.Size(75, 23);

 99             this.btnFolder.TabIndex = 5;

100             this.btnFolder.Text = "打开文件夹";

101             this.btnFolder.UseVisualStyleBackColor = true;

102             this.btnFolder.Click += new System.EventHandler(this.btnFolder_Click);

103             // 

104             // btnRename

105             // 

106             this.btnRename.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));

107             this.btnRename.Location = new System.Drawing.Point(363, 393);

108             this.btnRename.Name = "btnRename";

109             this.btnRename.Size = new System.Drawing.Size(75, 23);

110             this.btnRename.TabIndex = 7;

111             this.btnRename.Text = "重命名";

112             this.btnRename.UseVisualStyleBackColor = true;

113             this.btnRename.Click += new System.EventHandler(this.btnRename_Click);

114             // 

115             // txtPath

116             // 

117             this.txtPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)

118                         | System.Windows.Forms.AnchorStyles.Right)));

119             this.txtPath.Location = new System.Drawing.Point(12, 12);

120             this.txtPath.Name = "txtPath";

121             this.txtPath.ReadOnly = true;

122             this.txtPath.Size = new System.Drawing.Size(332, 21);

123             this.txtPath.TabIndex = 1;

124             this.txtPath.TextChanged += new System.EventHandler(this.txtPath_TextChanged);

125             // 

126             // txtSearch

127             // 

128             this.txtSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));

129             this.txtSearch.Location = new System.Drawing.Point(350, 12);

130             this.txtSearch.Name = "txtSearch";

131             this.txtSearch.Size = new System.Drawing.Size(111, 21);

132             this.txtSearch.TabIndex = 2;

133             // 

134             // btnUp

135             // 

136             this.btnUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));

137             this.btnUp.Location = new System.Drawing.Point(467, 10);

138             this.btnUp.Name = "btnUp";

139             this.btnUp.Size = new System.Drawing.Size(75, 23);

140             this.btnUp.TabIndex = 3;

141             this.btnUp.Text = "上级目录";

142             this.btnUp.UseVisualStyleBackColor = true;

143             this.btnUp.Click += new System.EventHandler(this.btnUp_Click);

144             // 

145             // btnAdd

146             // 

147             this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));

148             this.btnAdd.Location = new System.Drawing.Point(260, 393);

149             this.btnAdd.Name = "btnAdd";

150             this.btnAdd.Size = new System.Drawing.Size(75, 23);

151             this.btnAdd.TabIndex = 6;

152             this.btnAdd.Text = "新建文件夹";

153             this.btnAdd.UseVisualStyleBackColor = true;

154             this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);

155             // 

156             // cmsStyle

157             // 

158             this.cmsStyle.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {

159             this.大图标ToolStripMenuItem,

160             this.详细信息ToolStripMenuItem,

161             this.平铺ToolStripMenuItem,

162             this.小图标ToolStripMenuItem,

163             this.列表ToolStripMenuItem});

164             this.cmsStyle.Name = "cmsStyle";

165             this.cmsStyle.Size = new System.Drawing.Size(125, 114);

166             // 

167             // 大图标ToolStripMenuItem

168             // 

169             this.大图标ToolStripMenuItem.Checked = true;

170             this.大图标ToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;

171             this.大图标ToolStripMenuItem.Name = "大图标ToolStripMenuItem";

172             this.大图标ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);

173             this.大图标ToolStripMenuItem.Text = "大图标";

174             // 

175             // 详细信息ToolStripMenuItem

176             // 

177             this.详细信息ToolStripMenuItem.Name = "详细信息ToolStripMenuItem";

178             this.详细信息ToolStripMenuItem.Size = new System.Drawing.Size(152, 22);

179             this.详细信息ToolStripMenuItem.Text = "详细信息";

180             // 

181             // 平铺ToolStripMenuItem

182             // 

183             this.平铺ToolStripMenuItem.Name = "平铺ToolStripMenuItem";

184             this.平铺ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);

185             this.平铺ToolStripMenuItem.Text = "平铺";

186             // 

187             // 小图标ToolStripMenuItem

188             // 

189             this.小图标ToolStripMenuItem.Name = "小图标ToolStripMenuItem";

190             this.小图标ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);

191             this.小图标ToolStripMenuItem.Text = "小图标";

192             // 

193             // 列表ToolStripMenuItem

194             // 

195             this.列表ToolStripMenuItem.Name = "列表ToolStripMenuItem";

196             this.列表ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);

197             this.列表ToolStripMenuItem.Text = "列表";

198             // 

199             // MainForm

200             // 

201             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);

202             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

203             this.ClientSize = new System.Drawing.Size(554, 432);

204             this.Controls.Add(this.btnAdd);

205             this.Controls.Add(this.btnUp);

206             this.Controls.Add(this.txtSearch);

207             this.Controls.Add(this.txtPath);

208             this.Controls.Add(this.btnRename);

209             this.Controls.Add(this.btnFolder);

210             this.Controls.Add(this.btnDelete);

211             this.Controls.Add(this.lvwData);

212             this.Name = "MainForm";

213             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

214             this.Text = "ListView的使用";

215             this.Load += new System.EventHandler(this.MainForm_Load);

216             this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyDown);

217             this.cmsStyle.ResumeLayout(false);

218             this.ResumeLayout(false);

219             this.PerformLayout();

220 

221         }

222         #endregion

223 

224         private System.Windows.Forms.ListView lvwData;

225         private System.Windows.Forms.Button btnDelete;

226         private System.Windows.Forms.Button btnFolder;

227         private System.Windows.Forms.Button btnRename;

228         private System.Windows.Forms.TextBox txtPath;

229         private System.Windows.Forms.TextBox txtSearch;

230         private System.Windows.Forms.Button btnUp;

231         private System.Windows.Forms.Button btnAdd;

232         private System.Windows.Forms.FolderBrowserDialog fbdData;

233         private System.Windows.Forms.ImageList imgSmall;

234         private System.Windows.Forms.ImageList imgLarge;

235         private System.Windows.Forms.ContextMenuStrip cmsStyle;

236         private System.Windows.Forms.ToolStripMenuItem 大图标ToolStripMenuItem;

237         private System.Windows.Forms.ToolStripMenuItem 详细信息ToolStripMenuItem;

238         private System.Windows.Forms.ToolStripMenuItem 小图标ToolStripMenuItem;

239         private System.Windows.Forms.ToolStripMenuItem 列表ToolStripMenuItem;

240         private System.Windows.Forms.ToolStripMenuItem 平铺ToolStripMenuItem;

241     }

242 }
View Code

2.AddForm.cs及AddForm.Designer.cs

C#winform中ListView的使用
  1 using System;

  2 using System.Collections.Generic;

  3 using System.ComponentModel;

  4 using System.Data;

  5 using System.Drawing;

  6 using System.Linq;

  7 using System.Text;

  8 using System.Windows.Forms;

  9 using System.Text.RegularExpressions;

 10 

 11 namespace Controls

 12 {

 13     public partial class AddForm : Form

 14     {

 15         #region 公开字段及属性

 16         /// <summary>

 17         /// 检查输入是否为空

 18         /// </summary>

 19         public bool ButtonFlag = false;

 20 

 21         /// <summary>

 22         /// 文件夹名或文件名

 23         /// </summary>

 24         public string TxtName

 25         {

 26             get { return this.txtName.Text.Trim(); }

 27         }

 28         #endregion

 29 

 30         #region 初期化

 31         /// <summary>

 32         /// 默认构造函数

 33         /// </summary>

 34         public AddForm()

 35         {

 36             InitializeComponent();

 37             //给窗体注册键盘事件

 38             this.KeyPreview = true;

 39         }

 40 

 41         /// <summary>

 42         /// 构造函数,用于新增文件夹

 43         /// </summary>

 44         /// <param name="title">标题</param>

 45         public AddForm(string title)

 46             : this()

 47         {

 48             this.Text = title;

 49         }

 50 

 51         /// <summary>

 52         /// 构造函数,用于更新文件夹

 53         /// </summary>

 54         /// <param name="title">标题</param>

 55         /// <param name="name">内容</param>

 56         public AddForm(string title, string name)

 57             : this(title)

 58         {

 59             this.txtName.Text = name;

 60         }

 61         #endregion

 62 

 63         #region 事件处理

 64         /// <summary>

 65         /// 输入只能是字母、下划线、数字及中文字符

 66         /// </summary>

 67         /// <param name="sender"></param>

 68         /// <param name="e"></param>

 69         private void txtName_KeyPress(object sender, KeyPressEventArgs e)

 70         {

 71             //全选(1)、复制(3)、退格键(8)、粘贴(22)、下划线(95)

 72             int[] chars = { 1, 3, 8, 22, 95 };

 73             // 允许输入字母、下划线、数字、中文字符,允许全选、复制、删除、粘贴

 74             if (Char.IsLetter(e.KeyChar) || Char.IsDigit(e.KeyChar)

 75                 || (e.KeyChar >= 0x4e00 && e.KeyChar <= 0x9fa5) || chars.Contains(e.KeyChar))

 76             {

 77                 e.Handled = false;

 78             }

 79             else

 80             {

 81                 e.Handled = true;

 82             }

 83         }

 84 

 85         /// <summary>

 86         /// 粘贴时过滤不是字母,下划线,数字及中文的字符

 87         /// </summary>

 88         /// <param name="sender"></param>

 89         /// <param name="e"></param>

 90         private void txtName_TextChanged(object sender, EventArgs e)

 91         {

 92             TextBox textBox = sender as TextBox;

 93             //匹配字母,下划线,数字及中文字符的正则表达式

 94             var reg = new Regex("^[A-Z|a-z|_|0-9|\u4e00-\u9fa5]*$");

 95             var str = textBox.Text.Trim();

 96             var sb = new StringBuilder();

 97             if (!reg.IsMatch(str))

 98             {

 99                 for (int i = 0; i < str.Length; i++)

100                 {

101                     if (reg.IsMatch(str[i].ToString()))

102                     {

103                         sb.Append(str[i].ToString());

104                     }

105                 }

106                 textBox.Text = sb.ToString();

107                 //定义输入焦点在最后一个字符

108                 textBox.SelectionStart = textBox.Text.Length;

109             }

110         }

111 

112         /// <summary>

113         /// 提交信息

114         /// </summary>

115         /// <param name="sender"></param>

116         /// <param name="e"></param>

117         private void btnSave_Click(object sender, EventArgs e)

118         {

119             //新增或编辑文件夹名或文件名

120             if (txtName.Text.Trim() != "")

121             {

122                 ButtonFlag = true;

123                 this.Close();

124             }

125             else

126             {

127                 MessageBox.Show(this.lblName.Text + "不能为空!", "提示");

128             }

129         }

130 

131         /// <summary>

132         /// 给确定按钮添加快捷键

133         /// </summary>

134         /// <param name="sender"></param>

135         /// <param name="e"></param>

136         private void AddForm_KeyDown(object sender, KeyEventArgs e)

137         {

138             if (e.KeyCode == Keys.Enter)

139             {

140                 this.btnSave_Click(sender, e);

141             }

142         }

143         #endregion

144     }

145 }
View Code
C#winform中ListView的使用
 1 namespace Controls

 2 {

 3     partial class AddForm

 4     {

 5         /// <summary>

 6         /// Required designer variable.

 7         /// </summary>

 8         private System.ComponentModel.IContainer components = null;

 9 

10         /// <summary>

11         /// Clean up any resources being used.

12         /// </summary>

13         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

14         protected override void Dispose(bool disposing)

15         {

16             if (disposing && (components != null))

17             {

18                 components.Dispose();

19             }

20             base.Dispose(disposing);

21         }

22 

23         #region Windows Form Designer generated code

24 

25         /// <summary>

26         /// Required method for Designer support - do not modify

27         /// the contents of this method with the code editor.

28         /// </summary>

29         private void InitializeComponent()

30         {

31             this.lblName = new System.Windows.Forms.Label();

32             this.txtName = new System.Windows.Forms.TextBox();

33             this.btnSave = new System.Windows.Forms.Button();

34             this.SuspendLayout();

35             // 

36             // lblName

37             // 

38             this.lblName.AutoSize = true;

39             this.lblName.Font = new System.Drawing.Font("宋体", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

40             this.lblName.Location = new System.Drawing.Point(11, 30);

41             this.lblName.Name = "lblName";

42             this.lblName.Size = new System.Drawing.Size(59, 13);

43             this.lblName.TabIndex = 0;

44             this.lblName.Text = "文件夹名";

45             // 

46             // txtName

47             // 

48             this.txtName.Font = new System.Drawing.Font("宋体", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

49             this.txtName.Location = new System.Drawing.Point(78, 26);

50             this.txtName.Name = "txtName";

51             this.txtName.Size = new System.Drawing.Size(171, 22);

52             this.txtName.TabIndex = 1;

53             this.txtName.TextChanged += new System.EventHandler(this.txtName_TextChanged);

54             this.txtName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtName_KeyPress);

55             // 

56             // btnSave

57             // 

58             this.btnSave.Font = new System.Drawing.Font("宋体", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

59             this.btnSave.Location = new System.Drawing.Point(259, 26);

60             this.btnSave.Name = "btnSave";

61             this.btnSave.Size = new System.Drawing.Size(60, 22);

62             this.btnSave.TabIndex = 2;

63             this.btnSave.Text = "确定";

64             this.btnSave.UseVisualStyleBackColor = true;

65             this.btnSave.Click += new System.EventHandler(this.btnSave_Click);

66             // 

67             // AddForm

68             // 

69             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);

70             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

71             this.ClientSize = new System.Drawing.Size(334, 72);

72             this.Controls.Add(this.btnSave);

73             this.Controls.Add(this.txtName);

74             this.Controls.Add(this.lblName);

75             this.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

76             this.MaximizeBox = false;

77             this.Name = "AddForm";

78             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

79             this.Text = "新建文件夹";

80             this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.AddForm_KeyDown);

81             this.ResumeLayout(false);

82             this.PerformLayout();

83 

84         }

85 

86         #endregion

87 

88         private System.Windows.Forms.Label lblName;

89         private System.Windows.Forms.TextBox txtName;

90         private System.Windows.Forms.Button btnSave;

91     }

92 }
View Code

 3.添加文件夹及图片资源

1.文件夹Resource目录下包含:文件夹图片C#winform中ListView的使用(folder.png),文件图片C#winform中ListView的使用(file.png)两个文件

2.为ImageList(imgLarge,imgSmall)控件添加Images属性、设置ImageSize属性(imgLarge--40*40, imgSmall--20*20)

===相关参考链接===

1.C#winform中ListView及ContextMenuStrip的使用:http://www.cnblogs.com/makesense/p/4079835.html

2.C#winform点击ListView列标题进行排序:http://bbs.csdn.net/topics/350071962

3.C#删除文件和文件夹到回收站:http://www.cnblogs.com/lazycoding/archive/2012/09/25/2702007.html

你可能感兴趣的:(ListView)