如何在文本框中显示datagrid视图数据 [英] How to display datagrid view data in textbox

查看:73
本文介绍了如何在文本框中显示datagrid视图数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试在文本框中显示datagridview数据。

我为此编写代码并显示但只显示表的最后一条记录

我的代码如下所示



我尝试过:



int id;

id = Convert.ToInt32(dgproduct.Rows [e.RowIndex] .Cells [id]。Value.ToString());



SqlConnection connection = new SqlConnection(cn);

SqlCommand cmd = new SqlCommand(select * from myname,connection);

DataTable dt = new DataTable( );

SqlDataAdapter da = new SqlDataAdapter(cmd);



connection.Open();

da .Fill(dt);

foreach(dt.Rows中的DataRow dr)

{

txtpid.Text = dr [ID] .ToString();

txtpname.Text = dr [Name]。ToString();

}

c onnection.Close();

Hi I am trying to display datagridview data in text box.
I wrote code for that and it is showing but only the last record of the table
my code is as below

What I have tried:

int id;
id = Convert.ToInt32(dgproduct.Rows[e.RowIndex].Cells["id"].Value.ToString());

SqlConnection connection = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand("select * from myname", connection);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);

connection.Open();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
txtpid.Text = dr["ID"].ToString();
txtpname.Text = dr["Name"].ToString();
}
connection.Close();

推荐答案

由于你正在从表中选择*,它将获取整个数据并在循环中它将最后一个索引值分配给文本框。

你应该使用 where 子句选择确切的项目并分配结果到文本框。



Since you are doing "Select * from table" it will fetch the whole data and in the loop it will assign the last index value to the textbox.
you shall select the exact item using where clause and assign the result to text boxes.

SqlCommand cmd = new SqlCommand("select top 1 * from myname where id = @id", connection);
       cmd.Parameters.Add("@id", id);
       DataTable dt = new DataTable();


这篇关于如何在文本框中显示datagrid视图数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆