1

I have a gridview and i am adding two buttons "Edit and Delete" dynamically(by code). Here is my HTML Code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="4"
                BorderWidth="1px" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" />
                <FooterStyle BackColor="#990000" ForeColor="White" Font-Bold="True" />
                <HeaderStyle Height="30px" BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <PagerStyle ForeColor="#333333" HorizontalAlign="Center" BackColor="#E2E2E2" />
                <RowStyle CssClass="test" BackColor="#E2E2E2" Height="25px" BorderWidth="1px" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2E2E2" Font-Bold="True" ForeColor="Navy" />
                <SortedAscendingCellStyle BackColor="#FDF5AC" />
                <SortedAscendingHeaderStyle BackColor="#4D0000" />
                <SortedDescendingCellStyle BackColor="#FCF6C0" />
                <SortedDescendingHeaderStyle BackColor="#820000" />
            </asp:GridView>

Here is my Code Behind Code ::

 private void BindData(DataTable dtColumns)
{
    GridView1.Columns.Clear();
    String Query = "";
    DataTable dtSearchItems = (DataTable)ViewState["dtSearchItems"];
    String PrimaryKey = "";
    if (ViewState["PrimaryKey"] != null)
    {
        PrimaryKey = ViewState["PrimaryKey"].ToString();
    }
    if (dtColumns != null)
    {
        String Columns = "";
        if (dtColumns.Rows.Count > 0)
        {
            foreach (DataRow dr in dtColumns.Rows)
            {
                Columns += dr["OrignalColumn"].ToString() + ",";
            }
            Columns = Columns.TrimEnd(',');
            Query = "Select " + PrimaryKey + " , " + Columns + " from " + TableName + " where 1 = 1 ";
        }
        else
        {
            Query = "Select *," + PrimaryKey + " from " + TableName + " where 1 = 1 ";
        }
    }
    else
    {
        Query = "Select *," + PrimaryKey + " from " + TableName + " where 1 = 1 ";
    }
    if (dtSearchItems != null)
    {
        if (dtSearchItems.Rows.Count > 0)
        {
            foreach (DataRow dr in dtSearchItems.Rows)
            {
                Query += " " + dr["AndOr"].ToString() + " " + dr["ColumnName"].ToString() + " " + ClsStaticSearch.ReturnOperationSymbol(dr["Operation"].ToString(), dr["Value"].ToString());
            }
        }
        else
        {
            Query = Query;
        }
    }

    DataTable dtOutPutResult = new DataTable();
    SqlConnection con = new SqlConnection();
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
    SqlCommand cmd = new SqlCommand(Query, con);

    if (con.State == ConnectionState.Closed) con.Open();
    dtOutPutResult.Load(cmd.ExecuteReader());
    GridView1.DataKeyNames = new string[] { PrimaryKey };

    if (dtOutPutResult.Rows.Count > 0)
    {
        foreach (DataColumn dcDtOutPutResult in dtOutPutResult.Columns)
        {
            foreach (DataRow drDtColumns in dtColumns.Rows)
            {
                if (drDtColumns["OrignalColumn"].ToString() == dcDtOutPutResult.ColumnName)
                {
                    BoundField bfield = new BoundField();
                    bfield.DataField = dcDtOutPutResult.ColumnName;
                    bfield.HeaderText = drDtColumns["DisplayColumn"].ToString();
                    GridView1.Columns.Add(bfield);
                }
            }
        }

        TemplateField t = new TemplateField();
        DynamicTemplate mt = new DynamicTemplate(ListItemType.Item);

        Button btnEdit = new Button();
        btnEdit.ID = "btnEdit";
        btnEdit.Visible = true;
        btnEdit.OnClientClick = "return confirm_Edit();";
        btnEdit.Text = " Submit";
        btnEdit.CssClass = "button";
        btnEdit.Style.Add("margin-right", "5px");
        mt.AddControl(btnEdit, "Text", "Edit");

        Button btnDelete = new Button();
        btnDelete.ID = "btnDelete";
        btnDelete.OnClientClick = "return confirm_delete();";
        btnDelete.Visible = true;
        btnDelete.Text = " Submit";
        btnDelete.CssClass = "button";
        mt.AddControl(btnDelete, "Text", "Delete");

        t.ItemTemplate = mt;
        t.HeaderText = "Activity";
        GridView1.Columns.Add(t);
        GridView1.DataSource = dtOutPutResult;
        GridView1.DataBind();
        lblMessage.Visible = false;
    }
    else
    {
        GridView1.DataSource = dtOutPutResult;
        GridView1.DataBind();
        lblMessage.Visible = true;
        lblMessage.Style.Add("Color", "Red");
        lblMessage.Text = "No Record Found.";
    }
    cmd.Dispose();
}

What i want to do is::

I want to create a generic module for advanced search, that is almost complete, now what i want to do it it is: i want to add edit and delete functionality to grid also. for that i need to get DataKey Value of the grid for each button's click only by javascript or jquery because the buttons will not be visible if the page is being post back.

Please help me.

0

1 Answer 1

5

using hiddenfield to fetch value is very common solution for this scenario

<asp:TemplateField>
   <ItemTemplate>
     <asp:HiddenField ID="key" runat="server" Value='<%#Eval("ID") %>' />
   </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
  <ItemTemplate>
    <a href="#" id="getID">Read data key</a>
  </ItemTemplate>
</asp:TemplateField>

Script

<script type="text/javascript">
    $(document).ready(function() {
        $("table[id*=gridviewid] a[id*=getID]").click(function() {
            alert($(this).closest("tr").find("input[type=hidden][id*=key]").val());
        });
    });
</script>

If you find this tedious, you can find similar questions and solutions below:

With Jquery

On mouse over

Code project article

Fetching selected row datakey - stackoverflow

Sign up to request clarification or add additional context in comments.

2 Comments

your title didnt explain about the scenario or a mention any particular situation. in that case, if you want all the people to read your 40 lines of code than answering it, better mention it in the title.
@codebrain: If his problem needs more explanation or code then its fine to add it in question .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.