如何使用foreach循环读取数据表
问题描述:
我想在搜索数据时使用foreach循环进行迭代以遍历数据表。下面是搜索按钮的代码,其中输入地址并按下搜索按钮,应用程序必须从googlemaps返回GPS坐标,街道地址,省等,但它不会返回任何内容。请协助。代码如下。
I want to iterate using a foreach loop to loop through a datatable when I search for data. Below is code for a search button where an address is entered and a search button is pressed and the application must return GPS coordinates, street address, province etc from googlemaps but it does not return anything. Please assist. Code below.
private void btnSearch_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtSearchText.Text) || String.IsNullOrWhiteSpace(txtSearchText.Text))
{
MessageBox.Show("Enter a Search value", "You have not entered any address to search", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
AddressServiceData _AddressServiceData = new AddressServiceData();
try
{
DataTable DV = new DataTable();
string Address = string.Empty;
foreach (DataRow row in DV.Rows)
{
Address = row["Address1"].ToString();
DV = _AddressServiceData.GetGoogleSearch("", Address=txtSearchText.Text + " South Africa", "", "");
}
gridView1.Columns.Clear();
grdaddress.DataSource = DV;
gridView1.BestFitColumns();
AddressClassNew.SearchAttempt = true;
}
catch
{
AddressClassNew.SearchAttempt = true;
MessageBox.Show("Could not find Address");
return;
}
}
答
逐步完成逻辑。如果要迭代数据表的行,那么在尝试循环遍历行之前需要将行放入其中。
在代码中,声明一个名为DV 。此数据表中没有行,因此 foreach
将永远不会执行其内部代码块。我想你可能想要遍历除DV以外的DataTable对象。还有另一个你应该使用的吗?
Step through your logic. If you want to iterate through the rows of a datatable, then you need to put rows into it before you try to loop through the rows.
In your code, you declare a new instance of DataTable calledDV
. There are no rows in this datatable so yourforeach
will never execute its internal code block. I''m thinking that you may have wanted to loop through a DataTable object other than DV. Is there another one that you should be using?