how to get id of row from check box in gridview row


this is my gridview code  

<asp:GridView ID="dgAssociatedAttributes" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" Width="80%">

<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />

<RowStyle BackColor="#EEEEEE" ForeColor="Black" />

<Columns>

          <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="60%"/>

          <asp:TemplateField HeaderText="Is Required" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="25%" >

         <ItemTemplate>

                  <asp:CheckBox ID="chkIsRequired" runat="server" Checked='<%# Eval("IsRequired") %>' AutoPostBack="true"  OnCheckedChanged="IsRequired_Click" />

          </ItemTemplate>

</asp:TemplateField>

<asp:TemplateField ItemStyle-Width="39%">

     <ItemTemplate >

        <asp:LinkButton ID="lbDelete" runat="server" CausesValidation="false" CommandArgument='<%# Eval("AttributeId") %>' OnCommand="lbDelete_Click" >Delete</asp:LinkButton>

     </ItemTemplate>

</asp:TemplateField>

</Columns>

<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="#DCDCDC" />

</asp:GridView>

i want that when i check or uncheck the checkbox it fire a event

protected void IsRequired_Click(object sender, EventArgs e)

{

productId =
Convert.ToInt32(Request.QueryString["productId"]);

CheckBox checkbox = sender as CheckBox;

if (checkbox != null)

{

GridViewRow row = checkbox.NamingContainer as GridViewRow;

int attributeId = 0;

if (row != null)

{

int.TryParse(dgAssociatedAttributes.DataKeys[row.RowIndex].ToString(), out attributeId);

}

if (checkbox.Checked)

{

db.updateIsRequired(productId, attributeId,
true);

}

else

{

db.updateIsRequired(productId, attributeId,
false);

}

LoadAssociatedAttributes();

}

}

 

in this code i simply insert the checked value in database through store procedure

but problem is that i am not able to get the value of "attributeid" . i thought in "EventArgs e" i will b able to get the value like i get it with

"e.CommandArgument" in delete button click event . but here "e" is returning null

now how can i get the value of attribute id (the id of row that checkbox is clicked).

plz help me out on this .thanks in advance

Ahtesham

0
Ahtesham
8/4/2008 12:18:01 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies
855 Views

Similar Articles

[PageSpeed] 22

You can easily retrieve the primary key of your data as you are currently doing, but no where in your GridView declaration do I see that you have the DataKeyNames property defined. You must first add the name of your primary key field to this property if you expect to receive a value out of it later.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
8/4/2008 12:27:39 PM

 Make the following changes.

1. Add an invisible label to that gridview itemtemplate

<ItemTemplate>

                  <asp:CheckBox ID="chkIsRequired" runat="server" Checked='<%# Eval("IsRequired") %>' AutoPostBack="true"  OnCheckedChanged="IsRequired_Click" />

                  <asp:Label ID="lblId" runat="server"  Visible="false" Text='<%# Bind("TableId")'   />

          </ItemTemplate>

2. Now in checkbox changed event,

CheckBox chk = (CheckBox)sender;

GridViewRow gvRow = (GridViewRow)chk.NamingContainer;

Label lblId = (Label)gvRow.FindControl("lblId");

string tableid = lblId.Text;

I think you are vb.net programmer. understand the point and make in c#. Use Covnersion tools

labs.developerfusion.co.uk/convert/csharp-to-vb.aspx


Give a man a fish and you feed him for a day. Teach a man to fish and you feed him forever.
0
ramireddyindia
8/4/2008 12:35:30 PM

<script runat="server">
    String mac;                         // This is used to store the TableCell 'userid' within the Gridview
    //String hostName;                  // This is used to store the TableCell 'Host Name' within the Gridview
    String activity;                    // This is used to store the TableCell 'Activity within the Gridveiw
    String buildingNo;                  // This is used to store the TableCell 'Building# within the Gridveiw
    String description2;                // This is stored in the table 'user1' decription.
    String NASEuser;                    // This is used to store UserName to retrieve email form database
    String userEmail;                   // This is used to store the user's Email

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // This will assign the String variables their values pulling them from
        // the gridview.
 if (e.CommandName == "Update")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow selectedRow = GridView1.Rows[index];
            TableCell userid = selectedRow.Cells[1];
            mac = userid.Text;
            TableCell BuildingNo = selectedRow.Cells[2];
            buildingNo = BuildingNo.Text;
            //TableCell ComputerName = selectedRow.Cells[5];
            //hostName = ComputerName.Text;
            TableCell ActivityName = selectedRow.Cells[3];
            activity = ActivityName.Text;
            description2 = activity + " BLDG " + buildingNo;       //This is inserted into the description column
                                                                   //within the 'user1' table
            TableCell UserName = selectedRow.Cells[6];
            NASEuser = UserName.Text;
        }
    }

    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        // First I have to read the table 'macreg' to verify that the 'SqlDataSourceGrid' inserted true or false
        // within the table 'macreg', column 'MACcomplete'.  If the checkbox within the gridview is checked, then
        // enabled will be true, else it will be false.
        try
        {
            String enabled;
            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ToString()))
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO [user1] ([userid], [passwd], [description]) VALUES (@userid, @passwd, @description)", cn);
                SqlCommand cmd2 = new SqlCommand("SELECT * FROM macreg WHERE userid ='" + mac + "'", cn);
                SqlDataReader rdr = cmd2.ExecuteReader();
                rdr.Read();
                enabled = rdr["MACcomplete"].ToString();
                rdr.Close();
                if (enabled == "True")
                {
                    //Parameters
                    cmd.Parameters.Add("@userid", SqlDbType.VarChar, 50);
                    cmd.Parameters.Add("@passwd", SqlDbType.VarChar, 64);
                    cmd.Parameters.Add("@description", SqlDbType.NVarChar, 512);

                    //Values
                    cmd.Parameters["@userid"].Value = mac;
                    cmd.Parameters["@passwd"].Value = mac;
                    cmd.Parameters["@description"].Value = description2;
                    cmd.ExecuteNonQuery();
                }
                cn.Close();
            }
        }
        catch (Exception err)
        {
            ErrorMessageLabel.Text = "ERROR OCCURRED ";
            ErrorMessageLabel.Text += err.Message;
            Response.Write(err);
        }     
    }

</script>

 

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceGrid"
         CellPadding="4" DataKeyNames="userid" ForeColor="#3B3A60" GridLines="None" PageSize="25" Font-Names="Palatino Linotype"
         BorderColor="#504E6C" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" Width="100%" OnRowUpdated="GridView1_RowUpdated" OnRowCommand="GridView1_RowCommand" Font-Size="Small" AllowPaging="True" AllowSorting="True">
        <FooterStyle BackColor="#2A203B" Font-Bold="True" ForeColor="White" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" />
        <Columns>
            <asp:CommandField ShowEditButton="True" EditText="Complete" >
                <ItemStyle ForeColor="#FF8000" />
            </asp:CommandField>
           
            <asp:BoundField DataField="userid" HeaderText="MAC" ReadOnly="True" SortExpression="userid" />
            <asp:BoundField DataField="BuildingNo" HeaderText="Building" ReadOnly="True" SortExpression="BuildingNo" >
                <ItemStyle HorizontalAlign="Center" />
            </asp:BoundField>
            <asp:BoundField DataField="ActivityName" HeaderText="Activity" ReadOnly="True" SortExpression="ActivityName" >
                <ItemStyle HorizontalAlign="Center" />
            </asp:BoundField>
            <asp:BoundField DataField="Device" HeaderText="Device" ReadOnly="True" SortExpression="Device" visible="False" />
            <asp:BoundField DataField="ComputerName" HeaderText="ComputerName" ReadOnly="True"
                SortExpression="ComputerName" >
                <ItemStyle HorizontalAlign="Center" />
            </asp:BoundField>
            <asp:BoundField DataField="UserName" HeaderText="User" ReadOnly="True" SortExpression="UserName" />
            <asp:BoundField DataField="DateRequested" HeaderText="Date Requested" SortExpression="DateRequested" DataFormatString="{0:g}" ReadOnly="True" />
            <asp:CheckBoxField DataField="MACcomplete" HeaderText="Completed" SortExpression="MACcomplete" />
        </Columns>
        <SelectedRowStyle BackColor="#FFE0C0" ForeColor="#2A203B" Font-Bold="True" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" Font-Size="Small" />
        <PagerStyle ForeColor="White" HorizontalAlign="Center" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" />
        <HeaderStyle BackColor="#2A203B" Font-Bold="True" ForeColor="White" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" />
        <AlternatingRowStyle BackColor="#EDEDED" ForeColor="#2A203B" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" />
        <RowStyle BackColor="White" ForeColor="#2A203B" BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" />
        <EditRowStyle BorderStyle="Solid" BorderWidth="10px" HorizontalAlign="Center" Font-Bold="True" Font-Overline="False" Font-Size="Small" Font-Underline="True" />
        <EmptyDataRowStyle BorderColor="#2A203B" BorderStyle="Solid" BorderWidth="10px" HorizontalAlign="Center" />       
        <EmptyDataTemplate>
            <font color="red">No Open Work Orders</font>
        </EmptyDataTemplate>
    </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSourceGrid" runat="server" ConnectionString="<%$ ConnectionStrings:SBRcs %>"
        SelectCommand="SELECT userid, BuildingNo, ActivityName, Device, ComputerName, SUBSTRING(UserName, 6, 20) AS UserName, MACcomplete, DateRequested FROM macreg WHERE (MACcomplete = @MACcomplete)"
        UpdateCommand="UPDATE macreg SET MACcomplete = @MACcomplete ,DateCompleted = getdate() WHERE (userid = @userid )">
        <SelectParameters>
            <asp:Parameter DefaultValue="False" Name="MACcomplete" Type="Boolean" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="MACcomplete" />
            <asp:Parameter Name="userid" />
        </UpdateParameters>
    </asp:SqlDataSource>


~~ Believe in Science, not religion. Science will always progress, religions will always collapse. ~~
0
TheDirtyBird
8/4/2008 12:42:12 PM

You can try this way.

fire a JavaScript function OnClick event of the checkBox.  (eg: OnClick = "test(this);")

and in that function u wil b able to write like this.

function test(obj)

{

document.getElementById('HiddenField').value = obj.parentElement.parentElement.children[3].children[1].children[0].innerText;

}

you can place a debugger and check for the exact value in trial and error method.

HTH

Muppidi.


~ Muppidi
0
pmuppidi
8/4/2008 12:45:26 PM

If the DataKeys aren't being defined for whatever reason, Why not just add an attribute to the checkbox itself?

 <ItemTemplate>

                  <asp:CheckBox ID="chkIsRequired" runat="server" Checked='<%# Eval("IsRequired") %>' MyKey='<%# Eval("IsRequired") %>AutoPostBack="true"  OnCheckedChanged="IsRequired_Click" />

    </ItemTemplate>

 

Then, in code, you could reference:

chk = e.FindControl("chkIsRequired")

 myVal =  chk.Attributes["MyKey"].ToString();

 

I've left out a lot of code, but hopefully it is clear what I am saying.

0
lajohnson2
8/4/2008 1:06:14 PM

ecbruck i did define as u said but still i was not able to get the required id

and thanks every one for sharing there code and try to help me but they are more complex for my knowledge i tried the ramireddyindia way and it did work .

Ahtesham

0
Ahtesham
8/5/2008 4:56:06 AM
Reply:

Similar Artilces:

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

check a checkbox in a gridview...then get the row id
I am inserting a checkbox in a gridview using a template field and I need to have the box checked depending on a 1 or 0 value from the database.  I've toyed with a few similar methods I've used in the past to fill in text boxes etc and can't get anything to work with the 'Checked' boolean. Also, when the box is checked, I'm having it autopostback to the server and I need to update the database value but I'm struggling trying to figure out the database row to update. any guidance is greatly apprecieated. thanks, Burr Howdy!  Have the Checked proper...

javascript: check all check box in a perticular row , when i check a checkbox i that perticuler row
Hi Friends,I have a gridview. and I am having checkboxes in all the columns and all the rows. Like it is about selecting subjects.My Problem is when I select a Checkbox in First column of any row, all the checkboxes in that particular row should also be selected.How can I do this... . I have done all checkboxes checked for column, but no idea about row.Please guide.Thanks. Hi, this can be done with the help of jQuery, a great & free javascript library. Take a look at this article: Check All Checkboxes in GridView using JQuery. Grz, Kris.Read my blog. Handy Firefox plugins for web dev...

How to delete row from GridView control
Hello,  I am working on an ASP.NET 2.0 app, and I am trying to wire up a "Delete" button to a gridview control on a form. Here is the code for the ASP :  <asp:GridView ID="gvInConditions" runat="server" AutoGenerateColumns="true" OnRowDeleting="gvInConditions_RowDeleting" DataKeyNames="Condition_ID" >         <Columns>                <asp:CommandField ButtonType="Button" SelectText=&...

Get the Row Number or Row ID
Hi, I am using Sybase Central v4.3 with Interactive SQL to query the SQL Commands. My concern is how to get the rownumber or row id in select queries. Is there any in built commands in the ASE. If not please suggest me how to get the rownumber. Thanks.... Unless i'm mistaken, ASE does not use a rowid... it can have a timestamp, but it is updated with every modification to the row. http://infocenter.sybase.com/help/topic/com.sybase.help.ase_15.0.blocks/html/blocks/blocks34.htm -- Cory Sane [TeamSybase] Certified Sybase Associate DBA for ASE 15.0 "Santhanam P" wrote...

Adding row (one at a time) in gridview on a button click. And cells of added row should contain controls like DROPDOWN LIST or TEXT BOX.
Dear Friends, I am in great need for the solution/hints/guidance of my requirement, if anyone can help with.  Let me explain what I need."I need a Gridview control on a webpage having following 5 columns/fields.     Column 1: It just has a "+" button in its header only (other cells for this column is empty)    Column 2: The Column header here is "FIELD" and  it should contain dropdown list (which is populated from some database)    Column 3: The Column header here is "Operator" and  it should ...

Data Controls insert rows into gridview then insert rows from gridview into SQL Table
Hello there, I'm still new at performing miracles with code . Currently I am having trouble with my latest coding adventure I have a web application which records jobs and labour assigned to jobs. The issue in particular I'm having is the way in which labour is to be assigned. I want to use standard controls (Textbox, Dropdownlist) to record the values into a gridview (ie,put multiple rows into the gridview using the controls). Then, when all the inserting is complete, the user clicks a submit button to insert all the rows from the gridview into a database table. The reason for...

passing of values of each row into javascript function on check box check in gridview
i had a HTML hidden field in item template of gridview which is bind with a column "jobid" from tha database and a checkbox in each row.on header template of gridview i had a check box called "checkall" which is used for checking all the check boxes in the grid. my problem is -- i want to retrive the jobid of each row on the "checkall" click in the java script . <asp:TemplateField > <ItemStyle Width="9%" /> <EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </EditItemTemplate> ...

passing of values of each row into javascript function on check box check in gridview #2
thanks for the reply but still i am facing a problem ---- how to get the checkbox value (checked/uncheck) present in the item template in the same java script function.if i  am checking the "checkall" checkbox in the gridview header template, i should get all the check box checked in the itemtemplate field and "jobid" value should go inside hidden field and while unchecking the "checkall" ,all the itemtemlate checkbox should uncheck.   if any of the checkbox in the itemtemplate is unchecked it should be removed from the hidden field.plzzzz He...

Get row info when an imagebutton on that row is clicked in a gridview
This is my gridview:<asp:GridView ID="GridView1" runat="server>   <Columns>      <asp:BoundField ...>      ...      <asp:TemplateField>         <ItemTemplate>            <asp:ImageButton ID="Button1" ImageUrl=... runat="server" OnClick="Button1_Click" />         </ItemTemplate>    ...

returning the database row ID from a selected row from a GridView
Hi I'd like to be able to display a gridView with rows of data, and when the user selects a row, somehow return the ID value for the respective row from the database, not the row in the gridView - if that makes sense. If possible, I don't want the ID displayed in the gridView. Thanks for any helpRichard Use DataKeyNames and SelectedDataKey Property of GridViewSomnath Mali.NET Developer , Pune INDIA.Please Mark As Answer If my reply helped you. I’m not sure what it is your describing; could you elaborate? ThanksRichard 1. <asp:GridView DataKeyNames="ProductID" Al...

Gridview Rows Backcolor getting reset when selecting a row
I have a list of rows in my gridview that list one or more entries per date.  I have coded the RowDataBound event so that all of the rows for a given date have the same backcolor.  Day 1 is white, Day 2 is yellow, Day 3 is white, day 4 is yellow - where each day could have multiple rows.  On each row, I also have an Edit imagebutton that allows each row to be edited via a separate panel and not in-line grid editing.  When I click on the Edit imagebutton, I set the gridviews selectedindex to that row and then using the skin for the grid, the selected row backco...

How to get the row index of a selected row in listview control
Can someone please tell me how to get the index of a selected row in a listview.  <ItemTemplate> <asp:LinkButton runat="server" class="linkButton" id="xxxxx" Text='<%#Eval("documenttype") %>' CommandName="OpenFile" CommandArgument='<%#Eval("DocumentKey") %>'></asp:LinkButton></ItemTemplate>what you have to do is, in itemcommand event of ListView, you have to get the value of row indexif(e.CommandName == "corrospondingcommaandname"){     &nb...

change row color when the user check a row in gridview
Hello! I am posting this as a new thread. I got the answer from Alen. I wasn't able to make it work. This is the code.protected void gvMessages_RowDataBound(object sender, GridViewRowEventArgs e) {if (e.Row.RowType == DataControlRowType.DataRow) {e.Row.Attributes.Add("onclick", "this.style.backgroundColor='red'");e.Row.Style["cursor"] = "hand"; } } What is not working? Try this: e.Row.Attributes.Add("OnClick", "this.style.backgroundColor = 'Red';"); Thanks,MaxLet Me Google That For You! Than...

Web resources about - how to get id of row from check box in gridview row - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 12/3/2015 9:50:47 PM