如何根据列名动态地从数据集中检索数据 [英] How to retrieve data from dataset dynamically according to column name

查看:105
本文介绍了如何根据列名动态地从数据集中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所在的软件需要在标签上显示数据。

我正在使用Datagrid视图,该视图使用数据集加载Excel文件,并使用已填充数据的相同数据集,可以在文本框中键入列名称,用户需要在其中显示标签上的数据。

一切正常但文本框为空时代码出错。

我还想要这个功能,如果用户想要显示三列中的信息,那么他就可以。我需要为15个标签实现相同的功能,这样如果有人只需要显示5个或10个标签的信息,他就会在文本框中输入相应的列名并留空。我无法找到任何解决方案。



我尝试过:



为了更好地理解,下面是代码的一部分以及通过在运行时键入列名或通过代码中的预定义类型列名从数据集中搜索数据的两种方法。我想在我的项目中实现Runtime的前一种方法。



label1.Text = ds1.Tables [0] .Rows [i] [@ textBox1.Text。 ToString()]。ToString();



label1.Text = ds1.Tables [0] .Rows [i] [Columnname1]。ToString();

I am on a software where I need to display Data on labels.
I am using a Datagrid view which loads an Excel file using Data set and by using same dataset which is already filled with Data, One can type Column name in Textboxes for which user needs to display Data on Labels.
Everything Works fine but when the textbox is empty Code trows an error.
I also want this functionality that if user want to display like information from three columns only then he can. I need to implement same thing for 15 labels so that if someone needs to show information from only 5 or 10 labels he will enter corresponding columns name in textboxes and leave rest empty. I am unable to find any solution for this.

What I have tried:

For better understanding, below is the portion of code and the two ways to search data from Data set by typing Column name in runtime or by predefined typed column names in code. I want to implement the former approach of Runtime in my project.

label1.Text = ds1.Tables[0].Rows[i][@textBox1.Text.ToString()].ToString();

label1.Text = ds1.Tables[0].Rows[i]["Columnname1"].ToString();

推荐答案

首先,您应检查各种文本框中的值,以确保它们有效。这将帮助您避免出现错误。



其次,您无法以您尝试的方式动态创建查询。您需要使用文本框中的值来查找行索引和列索引。然后,您可以使用这些索引值来引用数据集中的值。



第三,不要使用默认变量名称,如ds1,textBox1等。使用正确有意义的名称,你和其他人会知道他们的目的是什么。
Firstly you should check the values in the various textboxes to make sure they are valid. That will help you avoid the error you see.

Secondly, you cannot dynamically create a query in the way you are trying. You need to use the values from the textboxes to find the row and column indexes. You can then use those index values to reference the values from the dataset.

Thirdly, do not use default variable names like ds1, textBox1 etc. Use proper meaningful names so you, and others, will know what their purpose is.


这篇关于如何根据列名动态地从数据集中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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