How can I select a row from a datatable using two variable values?

一笑奈何 提交于 2019-12-24 10:10:07

问题


Alright, so what I'm attempting to do here, is select from a datatable all the rows that match two variables. First, I queried a SPList into a datatable. The datatable has two columns, Client ID, and Model Details. Here's some of the code, so hopefully you can get an idea of what I'm attempting.

//These are contained within a foreach loop, so will be different through each
//iteration through.
int iClientID = gdbData.GetClientID(iJobNumberID);
string strModelDetails = xeApprovalUpdate.GetAttribute("ModelDetails");
string strClientID = iClientID.ToString()
//Here my datatable is populated from the sharepoint list I query
DataTable dtabModelDetails = queryModelDetails(splModelDetails);
DataRow[] drModelDetails = dtabModelDetails.Select(strClientID, strModelDetails);

Seeing as that didn't work, I attempted to do the following select statement:

DataTable dtabModelDetails = queryModelDetails(splModelDetails);
string strDataExpression = "ClientID = " + strClientID + " AND Title = " + strModelDetails;
DataRow[] drModelDetails = dtabModelDetails.Select(strDataExpression);

Now I'm getting a syntax error for the select statement, but I'm pretty sure my syntax is correct? Would I get this error if my select statement returned no rows?


回答1:


Yes, you can add where clause to the DataTable Select method like this....

DataRow[] drModelDetails = dtabModelDetails.Select("Client ID = '" + clientId + "' AND Model Details = '" + modelDetails + "'");



回答2:


Yes, you can add parameters to the SqlCommand object. Add one param for each param in your select statement.

Also, if you have spaces in your column names, you need to put them in brackets.

    DataRow[] drModelDetails = dtabModelDetails.Select("[Client ID] = @ClientID AND [Model Details] =@ModelDetails")

    cmd.Parameters.Add(new SqlParameter("@ClientID", ClientID));
    cmd.Parameters.Add(new SqlParameter("@ModelDetails", ModelDetails));


来源:https://stackoverflow.com/questions/6363448/how-can-i-select-a-row-from-a-datatable-using-two-variable-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!