前一篇文章完成了DataGridView控件的数据源绑定工作,并成功显示数据。但是数据绑定缺坞赕滴喋陷太大,没有灵活性,不能通过代码添加数据与修改数据。軎烩蔡怒今天,就来给大伙讲解如何通过代码给DataGridView控件添加数据。
工具/原料
VisualStudioC#2010
方法/步骤
1、1.建立WinForm项目,大伙都会,就不说过程了。然后将DataGridView控件拖到WinForm窗体中,呈现灰色(在第一篇中有讲解步骤)。
2、2.点击DataGridView控件右上角的箭头,然后选择“编辑列”。
3、3.在出现的“编辑列”界面中,点击添加。
4、4.在“添加”界面中,编辑“名称”和“页眉文本”。“名称”会在后台代码中引用,最好设置成英文;“页眉文本”是DataGridView控件中显示的列名。
5、5.照此方法,分别添加:姓名、性别、年龄三列,然后点击完成。你会看到DataGridView控件中已经出现新添加的三列,表示添加成功。
6、6.添加一个按钮(Button控件,此控件在左侧工具箱中),将其拖到WinForm窗体中。
7、7.右键Button控件,选择“属性”,弹出属性窗口。
8、8.修改Butto艘绒庳焰n控件的显示文本。在属性窗口中找到Text属性,将其从“button1”修改为“添加数据”,Button控件的显示文本就变为“添加数据”
9、9.双击按钮,转到代码编辑界面,在此编写代码。
10、10饱终柯肢.编写给DataGridView控件添加数据的代码。privatevoidbutton1_Click(objectsender,EventArgse){//添加数据骀旬沃啭时,类型都是默认的字符串类型stringname="Jim";stringgender="男";stringage="18";//将上面三个变量合成一个数组string[]row={name,gender,age};//给dataGridView1控件添加数据dataGridView1.Rows.Add(row);}
11、11.运行程序(调试),在显示的界面中点击按钮,DataGridView控件成功显示数据。