0

I have a GridView and I would like to be able to select multiple rows and get the data from the column mobilenumber and add it to list of type string. How do I that? This is what I tried but the code gives me error.

protected void Button1_Click(object sender, EventArgs e)
{
    List<string> selectedRows = new List<string>();
    foreach (DataGridViewRow row in GridView1.SelectedRows)
    {
        string currentRow = string.Empty;
        foreach (DataGridViewCell cell in row.Cells)
        {
            currentRow += String.Format("{0} ", cell.FormattedValue);
        }
        selectedRows.Add(currentRow);
    }
    for (int i = 0; i < selectedRows.Count; i++)
    {
        this.listBox1.Items.Add(selectedRows[i]);
    }
}

aspx -

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" style="margin-left: 78px; margin-right: 0px">
    <columns>
        <asp:BoundField DataField="MobileNumber" HeaderText="MobileNumber" />
    </columns>
</asp:GridView>
Ɖiamond ǤeezeƦ
  • 3,223
  • 3
  • 28
  • 40
  • Which error do you get? – Roman Feb 09 '17 at 10:16
  • @Roma - Error 6 'System.Web.UI.WebControls.GridView' does not contain a definition for 'SelectedRows' and no extension method 'SelectedRows' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found (are you missing a using directive or an assembly reference?) –  Feb 09 '17 at 10:17
  • GridView doesn't have a method/property called `SelectedRows`, the error message couldn't be much clearer. – DavidG Feb 09 '17 at 10:20
  • Usually in ASP.NET you use a checkbox in each row to have a multiple rows selection. See https://www.codeproject.com/articles/831115/how-to-get-multiple-selected-rows-from-gridview-in – Steve Feb 09 '17 at 10:22

2 Answers2

0

Your error shows that there isn't a SelectedRows property on a GridView control. Looking at the docs for GridView, the closest thing seems to be SelectedRow (singular). So it seems that the control doesn't normally allow you to select more than one row.

I found a tutorial which lets you add a checkbox to each GridView row in order to select multiple, and this might help you!

Ste Griffiths
  • 318
  • 5
  • 15
0

You can get the value of specific cell value by name.

Also FormattedValue returns an object and you are adding object to List<string> which will cause error so you need to call .ToString() method on FormattedValue

foreach (DataGridViewRow row in GridView1.SelectedRows)
{
  string currentRow = string.Empty;
  currentRow += String.Format("{0} ", row.Cells["MobileNumber"].FormattedValue.ToString());
  selectedRows.Add(currentRow);
}
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40