BrunoEarth
BrunoEarth

Reputation: 333

How to get a specific data in gridview using c#?

I was wondering how to retrieve a specific data from gridview. My database consists of columns like id, type and name. Lets say the contents of my gridview is like this example below:

Id         Type         Name

1         Guitar         Ibanez

2         Guitar         Gibson

What i want to happen is to get the value under Name, Lets say "Ibanez". I was able to retrieve the value for Id using datakeys but I can't figure out how to get the value of Name in Gridview. I included code below to better understand what i mean.

protected void GuitarBrandsGridViewBtn_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gridrow = btn.NamingContainer as GridViewRow;
    int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[gridrow.RowIndex].Value.ToString());
    con.Open();
    cmd.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
    cmd.Connection = con;
    int a = cmd.ExecuteNonQuery();
    con.Close();
    if (a > 0)
    {
        bindgridviewguitarbrands();
    }
    System.IO.File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItemsIbanezDetails" + id + ".aspx");
    System.IO.File.Delete(@"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItemsIbanezDetails" + id + ".aspx.cs");

}

Upvotes: 0

Views: 72

Answers (2)

nilay vayada
nilay vayada

Reputation: 14

you can use template field in the grid view instead of bound field like this :

<asp:TemplateField HeaderText="Name">
     <ItemTemplate>
          <asp:Label ID="lblName" runat="server" Text='<%# Eval("ColumnNameOfYourDatasourceForName") %>' />
     </ItemTemplate>
</asp:TemplateField>

and then get the label and its text in code behind from following code :

protected void GuitarBrandsGridViewBtn_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    GridViewRow gridrow = btn.NamingContainer as GridViewRow;

    Label lblName = gridrow.FindControl("lblName");
    string name = lblName.Text;

}

Upvotes: 0

Jim W
Jim W

Reputation: 5016

You can access specific columns like this

GuitarBrandsGridView.Rows[gridrow.RowIndex].Cells[1].Text;

Upvotes: 1

Related Questions