一、前言
本学期学习C#语言,学习窗口设计。本次综合大作业,我使用ListBox、ComboBox、Button等控件实现、并且能够显示txt文件的绝对路径、弹出消息提示等。细节处仍有不完善的地方。继续修改。
二、测试
测试txt文件,使用记事本输入几个课程名称。测试效果如图:
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 windowforms1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addBtn_Click(object sender, EventArgs e)
{
try//try语句捕捉异常
{ //采用if结构和if嵌套结构进行
if (courseCbo.SelectedIndex >=0 ) //索引值大于0,确保选中
FilelistBox.Items.Add(courseCbo.Items[courseCbo.SelectedIndex].ToString());
if(FilelistBox.Items.Count>=2)//利用计数器count来区分,选择是否重复
MessageBox.Show("已经选择了!", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (courseCbo.SelectedIndex < 0)//利用索引值,看看选择是.\否合法,不合法将弹出MesaageBox
MessageBox.Show("请选择课程!", "添加确认", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
//利用messagebox来提示。MessageBoxIcon来更改图标显示。
else//进行选课成功的提示
{
MessageBox.Show("选课成功!", "添加确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
}
}
catch
{
MessageBox.Show("请选择课程!", "添加确认", MessageBoxButtons.YesNo, MessageBoxIcon.Error); //捕捉异常
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
FilelistBox.Items.Clear();//清空
}
private void openBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDlg= new OpenFileDialog();//打开文件
openFileDlg.Filter = "txt(*.txt)|*.txt";//打开txt格式的文件
if(openFileDlg.ShowDialog() == DialogResult.OK )
{
try//异常捕捉
{
StreamReader srFile = new StreamReader(openFileDlg.FileName);
FiletextBox.Clear();
FiletextBox.Text=Path.GetFullPath(openFileDlg.FileName);//得到文件的绝对路径
string[] stringLines = File.ReadAllLines(FiletextBox.Text);//按照行读取txt文件的文本
foreach(string s in stringLines )
{
courseCbo.Items.Add(s);
}//按照行输出
srFile.Close();
}
catch(Exception)
{
MessageBox.Show("ERROR!");
}
}
}
private void FilelistBox_SelectedIndexChanged(object sender, EventArgs e)
{
FilelistBox.Text= courseCbo.Text;//将combox中选中的text文本在listbox中显示
}
private void removeBtn_Click(object sender, EventArgs e)
{
FilelistBox.Items.RemoveAt(courseCbo.SelectedIndex);//按照索引值移除
}
}
}