一、ImageList 和ListView
1、ImageList 添加图像
mageList组件,又称为图片存储组件,它主要用于存储图片资源,然后在控件上显示出来,这样就简化了对图片的管理。ImageList组件的主要属性是Images,它包含关联控件将要使用的图片。每个单独的图片可以通过其索引值或键值来访问。
2、ListView 中添加ImageList
二、DataGridView
C#Winform的DataGridView控件使用详解1—七种DataGridViewColumn类型使用方法_winform datagridview-CSDN博客
主要属性设置
1、Columns 设置
2、AutosizeColumnMode![](https://i-blog.csdnimg.cn/direct/364631475d744fd7b41f0d4a8fce2111.png)
加载csv 数据
#region 将CSV文件的数据读取到DataTable中
/// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public static System.Data.DataTable readCSV(string fileName)
{
if (!File.Exists(fileName))
{
MessageBox.Show("文件不存在");
return null;
}
DataTable dt = new DataTable();
try
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine = strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
int nullCount = 0;
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
if (aryLine[j] != "")
{
dr[j] = aryLine[j];
}
else
{
nullCount += 1;
}
}
if (nullCount >= 6)
{
}
else
{
dt.Rows.Add(dr);
}
}
}
sr.Close();
fs.Close();
return dt;
}
catch
{
return dt = null;
}
}
#endregion
加载数据源
/// <summary>
/// 加载数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 导入csv文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
DataTable dataTable = readCSV("D:\\test.csv");
dataGridView3.DataSource = dataTable;
}
导出CSV文件
private void 导出csv文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
//实例化SaveFileDialog
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存为csv文件";
//打开SaveFileDialog控件
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//数据流变量
Stream myStream;
//返回SaveFileDialog控件,并将所选择的文件转化成流
myStream = saveFileDialog.OpenFile();
//将选择的文件流生成写入流
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dataGridView3.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += ",";
}
columnTitle += dataGridView3.Columns[i].HeaderText;
}
//将内容写入文件流中
sw.WriteLine(columnTitle);
for (int j = 0; j < dataGridView3.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dataGridView3.Columns.Count; k++)
{
if (k > 0)
{
columnValue += ",";
}
if (dataGridView3.Rows[j].Cells[k].Value == null)
{
columnValue += "";
}
else if (dataGridView3.Rows[j].Cells[k].Value.ToString().Contains(","))
{
//将单元个中的,转义成文本
columnValue += "\"" + dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
}
else
{
//横向跳格
columnValue += dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
}
}
//内容写入文件流中
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
MessageBox.Show("导出表格成功!");
}
catch (Exception)
{
MessageBox.Show("导出表格失败!");
}
finally
{
sw.Close();
myStream.Close();
}
}
else
{
MessageBox.Show("取消导出表格操作!");
}
}
}
修改数据:
ContextMenuStrip
+DataGridView
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Console.WriteLine(e.RowIndex.ToString() +" , "+ e.ColumnIndex.ToString());
}
private void 修改单元格颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell != null)
{
int rowIndex = dataGridView1.CurrentCell.RowIndex;
int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
var cellValue = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
// 修改颜色
DataGridViewCell cell = dataGridView1.Rows[rowIndex].Cells[columnIndex];
cell.Style.BackColor = Color.Pink;
cell.Style.ForeColor = Color.Red;
dataGridView1.CurrentCell = cell;
MessageBox.Show($"行: {rowIndex}, 列: {columnIndex}, 值: {cellValue}");
}
else
{
MessageBox.Show("No cell is currently selected.");
}
}
/// <summary>
/// 多个单元格数值统一
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 选中单元格统一ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
cell.Value=11;
}
}
else
{
MessageBox.Show("No cells are selected.");
}
}
效果;
DataGridView+Button
int rowIndex = dataGridView1.CurrentCell.RowIndex;
int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
var cellValue = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
// 创建按钮单元格
DataGridViewButtonCell buttonCell = new DataGridViewButtonCell();
buttonCell.Value = "Click Me";
// 替换原有单元格
dataGridView1.Rows[rowIndex].Cells[columnIndex] = buttonCell;
DataGridView+CheckBox
// 设置某个单元格的值为复选框选中状态
dataGridView1.Rows[rowIndex].Cells[columnIndex] = new DataGridViewCheckBoxCell { Value = true }; // 选中状态
bool isChecked = (bool)dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
ContextMenuStrip
+ComboBox
DataGridViewComboBoxCell dataGridViewComboBoxCell = new DataGridViewComboBoxCell();
dataGridViewComboBoxCell.Items.Add("Items1");
dataGridViewComboBoxCell.Items.Add("Items2");
dataGridViewComboBoxCell.Items.Add("Items3");
dataGridViewComboBoxCell.Items.Add("Items4");
dataGridView1.Rows[rowIndex].Cells[columnIndex] = dataGridViewComboBoxCell;
DataGridView+Image
ImageList添加图像
关联图像
Image img = imageList1.Images[0];
//给ImageCell对象赋予图片的值,可以与imageList1控件关联
dataGridView1.Rows[rowIndex].Cells[columnIndex]=new DataGridViewImageCell { Value = img };
DataGridView+TextBoX
DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
dataGridViewTextBoxCell.Value = "文本";
dataGridView1.Rows[rowIndex].Cells[columnIndex] = dataGridViewTextBoxCell;
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestMain
{
public partial class DataGridViewTest : Form
{
public DataGridViewTest()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Console.WriteLine(e.RowIndex.ToString() +" , "+ e.ColumnIndex.ToString());
// 创建一个 DataGridViewButtonColumn
DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
buttonColumn.Name = "buttonColumn";
buttonColumn.HeaderText = "Actions";
buttonColumn.Text = "Click Me";
buttonColumn.UseColumnTextForButtonValue = true;
// 将按钮列添加到 DataGridView
// dataGridView.Columns.Add(buttonColumn);
int rowIndex = dataGridView1.CurrentCell.RowIndex;
int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
if (e.ColumnIndex==0&& e.RowIndex==0) // button
{
var cellValue = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
// 创建按钮单元格
DataGridViewButtonCell buttonCell = new DataGridViewButtonCell();
buttonCell.Value = "Click Me";
// 替换原有单元格
dataGridView1.Rows[rowIndex].Cells[columnIndex] = buttonCell;
}
else if (e.ColumnIndex == 1 && e.RowIndex ==0) // 复选框
{
// 设置某个单元格的值为复选框选中状态
dataGridView1.Rows[rowIndex].Cells[columnIndex] = new DataGridViewCheckBoxCell { Value = true }; // 选中状态
bool isChecked = (bool)dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
}
else if (e.ColumnIndex == 2 && e.RowIndex == 0) // 下拉框
{
DataGridViewComboBoxCell dataGridViewComboBoxCell = new DataGridViewComboBoxCell();
dataGridViewComboBoxCell.Items.Add("Items1");
dataGridViewComboBoxCell.Items.Add("Items2");
dataGridViewComboBoxCell.Items.Add("Items3");
dataGridViewComboBoxCell.Items.Add("Items4");
dataGridView1.Rows[rowIndex].Cells[columnIndex] = dataGridViewComboBoxCell;
}
else if (e.ColumnIndex == 3 && e.RowIndex == 0) // 图像
{
Image img = imageList1.Images[0];
//给ImageCell对象赋予图片的值,可以与imageList1控件关联
dataGridView1.Rows[rowIndex].Cells[columnIndex]=new DataGridViewImageCell { Value = img };
}
else if (e.ColumnIndex == 5 && e.RowIndex == 0) // 文本
{
DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
dataGridViewTextBoxCell.Value = "文本";
dataGridView1.Rows[rowIndex].Cells[columnIndex] = dataGridViewTextBoxCell;
}
}
private void 修改单元格颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell != null)
{
int rowIndex = dataGridView1.CurrentCell.RowIndex;
int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
var cellValue = dataGridView1.Rows[rowIndex].Cells[columnIndex].Value;
// 修改颜色
DataGridViewCell cell = dataGridView1.Rows[rowIndex].Cells[columnIndex];
cell.Style.BackColor = Color.Pink;
cell.Style.ForeColor = Color.Red;
dataGridView1.CurrentCell = cell;
MessageBox.Show($"行: {rowIndex}, 列: {columnIndex}, 值: {cellValue}");
}
else
{
MessageBox.Show("No cell is currently selected.");
}
}
/// <summary>
/// 多个单元格数值统一
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 选中单元格统一ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedCells.Count > 0)
{
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
cell.Value=11;
}
}
else
{
MessageBox.Show("No cells are selected.");
}
}
#region 将CSV文件的数据读取到DataTable中
/// <summary>
/// 将CSV文件的数据读取到DataTable中
/// </summary>
/// <param name="fileName">CSV文件路径</param>
/// <returns>返回读取了CSV数据的DataTable</returns>
public static System.Data.DataTable readCSV(string fileName)
{
if (!File.Exists(fileName))
{
MessageBox.Show("文件不存在");
return null;
}
DataTable dt = new DataTable();
try
{
FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
aryLine = strLine.Split(',');
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i]);
dt.Columns.Add(dc);
}
}
else
{
int nullCount = 0;
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
if (aryLine[j] != "")
{
dr[j] = aryLine[j];
}
else
{
nullCount += 1;
}
}
if (nullCount >= 6)
{
}
else
{
dt.Rows.Add(dr);
}
}
}
sr.Close();
fs.Close();
return dt;
}
catch
{
return dt = null;
}
}
#endregion
//保存数据到csv文件
private void btnSaveToCSV_Click(object sender, EventArgs e)
{
//实例化SaveFileDialog
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存为csv文件";
//打开SaveFileDialog控件
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//数据流变量
Stream myStream;
//返回SaveFileDialog控件,并将所选择的文件转化成流
myStream = saveFileDialog.OpenFile();
//将选择的文件流生成写入流
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dataGridView3.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += ",";
}
columnTitle += dataGridView3.Columns[i].HeaderText;
}
//将内容写入文件流中
sw.WriteLine(columnTitle);
for (int j = 0; j < dataGridView3.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dataGridView3.Columns.Count; k++)
{
if (k > 0)
{
columnValue += ",";
}
if (dataGridView3.Rows[j].Cells[k].Value == null)
{
columnValue += "";
}
else if (dataGridView3.Rows[j].Cells[k].Value.ToString().Contains(","))
{
//将单元个中的,转义成文本
columnValue += "\"" + dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
}
else
{
//横向跳格
columnValue += dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
}
}
//内容写入文件流中
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
MessageBox.Show("导出表格成功!");
}
catch (Exception)
{
MessageBox.Show("导出表格失败!");
}
finally
{
sw.Close();
myStream.Close();
}
}
else
{
MessageBox.Show("取消导出表格操作!");
}
}
/// <summary>
/// 加载数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void 导入csv文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
DataTable dataTable = readCSV("D:\\test.csv");
dataGridView3.DataSource = dataTable;
}
private void 导出csv文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
//实例化SaveFileDialog
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存为csv文件";
//打开SaveFileDialog控件
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//数据流变量
Stream myStream;
//返回SaveFileDialog控件,并将所选择的文件转化成流
myStream = saveFileDialog.OpenFile();
//将选择的文件流生成写入流
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
//写入列标题
for (int i = 0; i < dataGridView3.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += ",";
}
columnTitle += dataGridView3.Columns[i].HeaderText;
}
//将内容写入文件流中
sw.WriteLine(columnTitle);
for (int j = 0; j < dataGridView3.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dataGridView3.Columns.Count; k++)
{
if (k > 0)
{
columnValue += ",";
}
if (dataGridView3.Rows[j].Cells[k].Value == null)
{
columnValue += "";
}
else if (dataGridView3.Rows[j].Cells[k].Value.ToString().Contains(","))
{
//将单元个中的,转义成文本
columnValue += "\"" + dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
}
else
{
//横向跳格
columnValue += dataGridView3.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
}
}
//内容写入文件流中
sw.WriteLine(columnValue);
}
sw.Close();
myStream.Close();
MessageBox.Show("导出表格成功!");
}
catch (Exception)
{
MessageBox.Show("导出表格失败!");
}
finally
{
sw.Close();
myStream.Close();
}
}
else
{
MessageBox.Show("取消导出表格操作!");
}
}
}
}
三、MenuStrip
常用属性:
常用事件
private void 新增加学生ToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmAddTeacher frmAddTeacher = new FrmAddTeacher();
frmAddTeacher.MdiParent = this; // 设置当前窗体的父窗口
frmAddTeacher.Show();
}
注意:
C#被指定窗体的MdiParent的窗体不是MdiContainer 原创这个问题的原因是父窗体的IsMdiContainer 属性设置为false导致的。 将此属性设置为true,即可解决此问题
Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestMain
{
public partial class MenuStripTest : Form
{
public MenuStripTest()
{
InitializeComponent();
}
private void MenuStripTest_Load(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = new ToolStripMenuItem();
menuItem.Name = "老师";
menuItem.Text= "老师管理";
ToolStripMenuItem miAddTeacher= new ToolStripMenuItem();
miAddTeacher.Name = "miAddTeacher";
miAddTeacher.Text = "新增老师";
miAddTeacher.Click += OnAddTeacher_Click; // 添加Frame事件
menuItem.DropDownItems.Add(miAddTeacher);//添加子菜单
menuStrip1.Items.Add(menuItem); //添加主菜单
}
private void OnAddTeacher_Click(object sender, EventArgs e)
{
FrmAddTeacher frmAddTeacher = new FrmAddTeacher();
frmAddTeacher .MdiParent= this; // 设置当前窗体的父窗口
frmAddTeacher.Show();
}
private void button1_Click(object sender, EventArgs e)
{
FrmAddTeacher frmAddTeacher = new FrmAddTeacher();
frmAddTeacher.MdiParent = this; // 设置当前窗体的父窗口
frmAddTeacher.Show();
}
private void 新增加学生ToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmAddTeacher frmAddTeacher = new FrmAddTeacher();
frmAddTeacher.MdiParent = this; // 设置当前窗体的父窗口
frmAddTeacher.Show();
}
}
}
四、ContextMenuStrip
ContextMenuStrip
用于创建和显示上下文菜单,也就是通常所说的右键菜单。它通常与窗体或其他控件相关联,当用户在相关联的控件上右击时,上下文菜单就会显示出来。
属性
ContextMenuStrip 的一些重要属性包括:
Items:菜单项的集合,用于存放菜单项。
Name:菜单的名字。
除了这些,ContextMenuStrip 还有其他一些属性,例如 BackColor、ForeColor、Font 等,用于设置菜单的背景色、前景色、字体等。
方法
Show
:显示上下文菜单。该方法有多个重载版本,可以指定显示位置等参数。Hide
:隐藏上下文菜单。Dispose
:释放ContextMenuStrip
控件所使用的资源
关联:
这一步非常重要
示例:
五、ToolStrip
ToolStrip
通常用于创建工具栏,以便用户能够快速访问常用的命令或功能。ToolStrip
可以包含多个不同类型的项,例如按钮、标签、下拉按钮等。
示例:
/// <summary>
/// tool
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton1_Click(object sender, EventArgs e)
{
button2.BackColor = Color.Pink;
}
private void toolStripLabel1_Click(object sender, EventArgs e)
{
toolStripLabel1.Text = "toolStripLabel1_Click 测是";
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
button1.BackColor = Color.Blue;
}
private void toolStrip1_Click(object sender, EventArgs e)
{
this.BackColor = Color.Brown;
}
六、StatusStrip状态
StatusStrip
控件是通常用于在窗口的底部显示状态信息、进度条等
private void StatusStripTest_Load(object sender, EventArgs e)
{
// 创建StatusStrip控件
StatusStrip statusStrip = new StatusStrip();
statusStrip.Dock = DockStyle.Bottom;
// 添加账号信息
ToolStripStatusLabel accountLabel = new ToolStripStatusLabel();
accountLabel.Text = "账号: user1";
statusStrip.Items.Add(accountLabel);
// 添加角色信息
ToolStripStatusLabel roleLabel = new ToolStripStatusLabel();
roleLabel.Text = "角色: 管理员";
statusStrip.Items.Add(roleLabel);
// 添加操作位置信息
ToolStripStatusLabel locationLabel = new ToolStripStatusLabel();
locationLabel.Text = "操作位置: 主界面";
statusStrip.Items.Add(locationLabel);
// 添加进度条
ToolStripProgressBar progressBar = new ToolStripProgressBar();
progressBar.Value = 50;
statusStrip.Items.Add(progressBar);
// 添加版本信息
ToolStripStatusLabel versionLabel = new ToolStripStatusLabel();
versionLabel.Text = "版本: v1.0";
statusStrip.Items.Add(versionLabel);
// 将StatusStrip控件添加到窗口的Controls集合中
this.Controls.Add(statusStrip);
}