1,建立winform窗體應用程式
2,在介面上拖曳到DataGridView控制項
3,新增對應的列如圖:
4,開始寫後面的程式碼:
private DataTable CountryDt = new DataTable();
private DataTable CityDt = new DataTable();
{
InitializeComponent();
# }
private void InitCityDt( )
{
, "US|9|洛杉磯", "US|10|芝加哥", "US| 11|休士頓", "US|12|費城", "US|13|舊金山"};
CityDt.Columns.Add("cityCode");
Add("cityCode");
CityDt.Columns.Add("Pid");
for (int i = 0; i < city var newRow = CityDt.NewRow();
newRow["cityCode"] = citys[i].Split('|')[1];
newRow ["city"]" ## newRow["Pid"] = citys[i].Split('|')[0];
}
private void InitCountryDt ()
{
string[] countrys = { "CN|中國", "JP|日本", "US|美國" };
); # CountryDt.Columns.Add("countryName");
for (int i = 0; i < 約 var newRow = CountryDt.NewRow();
newRow["countryCode"] = countrys[i].Split('|')[0];
newRow["countryName"] = countrys[i].Split('|')[1];#countrys[i].Split('|')[1];# CountryDt.Rows.Add(newRow);
}
}
private void InitGrid()
> dt.Columns. Add("Id");
dt.Columns.Add("CountryCode");
dt.Columns.Add("CityCode")) dt i++)
{
var newRow = dt.NewRow();
遠 dt.Rows.Add(newRow);
}
dataGridView1.DataSource = dt;
private void btnAdd_Click(object s View1.DataSource as DataTable;
#var newRow = dt.NewRow();
newRow["Id"] = dt.Rows.Count + 1;
dt.Rows.Add(newRow);#
for (int i = 0; i {
ell.DataSource = CountryDt;
countryCell 。 = "countryCode";
countryCell.DisplayMember = "countryName";
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
var dt e.ColumnIndex].Name == nameof(CountryCode))
{
# {
# var CountryCode = dataGridView1.Rows[e.RowIndex].Cells "Pid='" + CountryCode + "'") ;
var newCityDt = new DataTable();
newCity ns.Add("cityName");
newC ityDt.Columns.Add(" Pid");
foreach (drs 中的DataRow 行)
();
newRow["cityCode"] = 排["城市代碼"];
newRow["cityName"] = row["cityName"];
newRow["Pid"] = row["Pid"] p.
}
var cityCell = new DataGridViewComboBoxCell();
##cityCell.DataSource = newCityDt;
city ";
dataGridView1.Rows [e .RowIndex].Cells["CityCode"] = cityCell;
}
}
for (int i = 0;我 {
var cell = new DataGrid ComboBoxCell()## DisplayMember = "countryName",
ValueMe mber = "countryCode",
};
dataGridView1.Rows[i].Cells["CountryCode"] = cell;
if (i % 2 == 0)
dataGridView1.Rows[i].Cells["CountryCode" ].Value = "JP";
dataGridView1.Rows[i].Cells["CityCode"].Value = new Random( ). //// else {
// dataGridView1.Rows[i].Cells["CountryCode"].Value = "CN";
i % 5 == 0)
{
dataGridView1.Rows[i].Cells["CountryCode"].Value = "CN";
dataGridView1.Rows[i].Cells["CityCode"]. 3) ;
}
if (i % 9 == 0)## dataGridView1.Rows[i].Cells["CountryCode"].Value = "US";
dataGridView1 .Rows [i].Cells["CityCode"].Value = new Random().Next(8, 13);
}
pri#. (object sender, EventArgs e)
{
var selected = dataGridView1.SelectedRows;
var dt 0)
{
for (var i = 0; i dt.Rows.RemoveAt(行中。指數);### }###
以上是如何實作DataGridView的新增刪除修改?的詳細內容。更多資訊請關注PHP中文網其他相關文章!