简体   繁体   English

从数据网格视图中选择多行并以逗号分隔的字符串格式添加到变量 C#

[英]Select multiple rows from data grid view and add to a variable in a comma separated string format C#

Trying to create a comma separated string based on the values the user selects on the data gridview.尝试根据用户在数据 gridview 上选择的值创建逗号分隔的字符串。 This is a windows form application.这是一个 windows 窗体应用程序。 The data grid view is called 'gvModelsToDelete' and currently I have the below code: ModelName in the code is the column I am after and consists of countries.数据网格视图称为“gvModelsToDelete”,目前我有以下代码:代码中的 ModelName 是我要查找的列,由国家/地区组成。 Eg user selects second row ('UK') and fourth row ('US').例如,用户选择第二行('UK')和第四行('US')。 I want the first column of the grid view to be concatenated to a string eg 'UK,US'.我希望将网格视图的第一列连接到一个字符串,例如 'UK,US'。 If user then selects 'EU' as well.如果用户也选择“EU”。 I expect the string to be: 'UK,US,EU'.我希望字符串是:'UK,US,EU'。

private void Delete_Click(object sender, System.EventArgs e)
{
    if (gvModelsToDelete.SelectedRows.Count != 0)
    {
        DataGridViewRow row = this.gvModelsToDelete.SelectedRows[0];
        modelName = row.Cells["MODEL_NAME"].Value.ToString();
    }
}

I need it as a comma-separated string, so I can parse it to a sql stored procedure!我需要它作为逗号分隔的字符串,所以我可以将它解析为 sql 存储过程! Right now it's only accepting one value so even if I select two, it takes the first one I have selected.现在它只接受一个值,所以即使我选择了两个,它也会接受我选择的第一个值。 How can I change the above code to loop through each selected row and concatenate into a string variable so I can use it to parse in as a parameter?如何更改上面的代码以遍历每个选定的行并连接成一个字符串变量,以便我可以使用它作为参数进行解析?

You just need to iterate through the selected rows:您只需要遍历选定的行:

private void Delete_Click(object sender, System.EventArgs e)
{
    if (gvModelsToDelete.SelectedRows.Count > 0)
    {
        modelName = "";
        foreach (DataGridViewRow row in gvModelsToDelete.SelectedRows)
        {
            if (string.IsNullOrEmpty(modelName)
            {
                modelName = row.Cells["MODEL_NAME"].Value.ToString();
            }
            else
            {
                modelName+= "," + row.Cells["MODEL_NAME"].Value.ToString();
            }
        }
    }
}

If you want to use LINQ and have something a little more terse, you can do this:如果你想使用 LINQ 并且有一些更简洁的东西,你可以这样做:

private void Delete_Click(object sender, System.EventArgs e)
{
    if (gvModelsToDelete.SelectedRows.Count > 0)
    {
        modelName = String.Join(",", 
            from row in gvModelsToDelete.SelectedRowsRows.Cast<DataGridViewRow>
            select row.Cells["MODEL_NAME"].Value.ToString();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM