DatagridView取字段值賦給textbox,搞出一個奇怪的值﹗﹗

一位从 Delphi 转投 C# 的新手开发者,在尝试将 DataGridView 中的数据赋值给 TextBox 时遇到问题。原本使用 .ToString() 方法获取单元格值,但在更改数据表后方法失效。通过加入字段名并使用 .Value 属性成功解决问题。

DatagridView取字段值賦給textbox,搞出一個奇怪的值﹗﹗

本來我也是從delphi轉到c#的新手﹐當我想將datagridview中的值給得textbox時﹐首先用.cells[index].tostring();

這樣本來可以﹐但數據表一改就完蛋了﹐從我搞delphi的經驗﹐我就在想應可以取字段呀﹐為什么沒這個字段東東呢﹖我憑感覺在cells[]中加上"pc_name",再一試搞出一個﹕DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=1 }每行都是這樣﹐只是rowindex=1再變化﹐好奇怪﹗﹗﹗﹐所以我拿delphi的經驗﹐在后面加一個value,先只是猜想﹐當我打上點后﹐真出來了一個.value,不管這么多﹐先加上去。一試真的出結果了。

pc_nameTextBox.Text = pc_hdDataGridView.Rows[pc_hdDataGridView.CurrentRow.Index].Cells["pc_name"].ToString(); 

pc_nameTextBox.Text = pc_hdDataGridView.Rows[pc_hdDataGridView.CurrentRow.Index].Cells["pc_name"].ToString(); 

好奇怪﹗﹗Dear Microsoft!!

有人能解釋一下這個嗎﹖

public partial class Purchase : Form { public Purchase() { InitializeComponent(); } public static DataTable SelectData(string sql) { SqlConnection conn = new SqlConnection(); //通过指定属性的方式直接赋值 //SQLEXPRESS //要连接的数据 要操作的数据库文件 采用window账号 密码的方式 conn.ConnectionString = "Server=湖映柳故人离\\SQL;Database=Text1;Trusted_Connection=true"; //最后一个参数表示默认的连接方式 conn.Open(); //写执行的命令 SqlCommand cmd = new SqlCommand(sql, conn);//指定一下是由哪个数据库执行的哪个命令 //把语句提交之后,得到一个返回的结果 SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; //表格 DataSet dataSet = new DataSet(); adapter.Fill(dataSet); DataTable table = dataSet.Tables[0]; //搞个变量接收一下最终的返回信息 conn.Close();//关闭数据库 return table; } private void button1_Click(object sender, EventArgs e) { // 第一部分:从数据库加载数据 DataTable table = SelectData("SELECT * FROM Table_2"); if (table.Rows.Count > 0) { // 可以将 table 绑定到 DataGridView 或进行其他处理 // dataGridView1.DataSource = table; } // 第二部分:处理购买逻辑 if (int.TryParse(textBox4.Text, out int quantity)) { if (comboBox1.SelectedIndex == -1) { MessageBox.Show("请先选择一个商品"); return; } var selectedItem = table.Rows[comboBox1.SelectedIndex]; if (selectedItem < quantity) { MessageBox.Show("库存不足!"); return; } // 减少库存 selectedItem.Number -= quantity; // 生成订单 Random random = new Random(); double totalPrice = quantity * selectedItem.Price; Form1.list1(new order(random.Next(1000, 3000), selectedItem.Name, quantity, totalPrice, DateTime.Now)); MessageBox.Show("购买成功"); } else { MessageBox.Show("请输入有效的数量"); } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < Form1.list.Count; i++) { if (comboBox1.SelectedIndex == i) { textBox2.Text = Form1.list[i].Price.ToString(); textBox3.Text = Form1.list[i].Number.ToString(); } } } private void Purchase_Load(object sender, EventArgs e) { for (int i = 0; i < Form1.list.Count; i++) { comboBox1.Items.Add(Form1.list[i].Name); } } } }
最新发布
09-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值