我正在使用GridView
我需要在现有列中添加按钮(将现有列转换为按钮列)不使用按钮添加新列。我的专栏名为Volunteers
。
请参阅以下代码:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
DataGridViewButtonXColumn bcx =
dataGridViewShowCourse.Columns["Volunteers"] as DataGridViewButtonColumn;// Like I did nothing
bcx.UseColumnTextForButtonValue = true;
bcx.Text = "ADD";
bcx.Name = "MyButton";
}
错误显示:Object reference not set to an instance of an object.
我知道用按钮添加新列但我不想这样做,我需要将按钮添加到现有列。使用下面的按钮添加新列的代码
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
dataGridViewShowCourse.Columns.Add(col);
由于
答案 0 :(得分:0)
您可以使用正确的设置在设置数据源之前添加新的按钮列:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
if(dataGridViewShowCourse.Columns["MyButton"] == null){
var col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
col.DataPropertyName = "Volunteers"; //<-- this is very important
dataGridViewShowCourse.Columns.Add(col);
}
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
}
但我建议您从Volunteers
删除SELECT
并自行添加新按钮列。
将列设置为最后一个:
col.DisplayIndex = dataGridViewShowCourse.Columns.Cast<DataGridViewColumn>()
.Count(col=>col.Visible) - 1;