var sb = new StringBuilder();
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (row.IsNewRow) continue; // 跳過新增行
var cell1 = row.Cells[1].Value; // 第 2 欄
var cell9 = row.Cells[9].Value; // 第 10 欄
if (cell1 != null && cell9 != null) {
sb.AppendFormat("圖書編號 {0} 有 {1} 本;\n", cell1, cell9);
}
}
string result = sb.ToString();
row.IsNewRow 避免處理資料繫結自動產生的新增佔位行。Cells[index].Value 並判斷 null,防止 NullReferenceException。StringBuilder 避免大量字串連接產生臨時物件。