Category Archives: SqlDataSource

SqlDataSource

[RESOLVED]How to pseudo click Update link button from javascript

Hi,

How can I click a Formview Update link button from javascript ?

Hi shtrudel,

From your description, if you want to add client event for update button, you could refer to the following code.

    <script type="text/javascript">
        function updateClick() {
            alert("Update?");
            return false;
            
        }
    </script>

        <asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSource1" OnItemUpdating="FormView1_ItemUpdating" DefaultMode="Edit">
            <EditItemTemplate>
                Id:
                <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name :
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                Gender :
                <asp:TextBox ID="GenderTextBox" runat="server" Text='<%# Bind("Gender") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClientClick="return updateClick();" CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            ...

        </asp:FormView>

If you want to trigger update button click event from JavaScript. You could refer to the following code.

document.getElementById('<%= FormView1.FindControl("UpdateButton").ClientID %>').click()

If you have any other questions about my reply, please let me know freely.

Best Regards,
Dillion

[RESOLVED]How to check the element of a control which is inside a grid using javascript

Hi guys,

I have a grid in which  in which first cell is check box 2nd is drop down 3 rd  cell have radio button  and 4th cell have label

Now condition is that if fisrt check box than check if  radio box is checked then value of selected item from drop down should get appended with 

the label which is in 4th cell.

How to do it 

You can try with the below implemenation

HTML:

<asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True"
                    DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_OnRowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
                                    DataTextField="AddressLine1" DataValueField="AddressLine1">
                                </asp:DropDownList>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:RadioButton ID="RadioButton1" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorks2008R2ConnectionString %>"
                    SelectCommand="SELECT top 20  [AddressID], [AddressLine1] FROM Person.Address">
                </asp:SqlDataSource>
            </ContentTemplate>
        </asp:UpdatePanel>

C#:

/// <summary>
        /// Handles the CheckedChanged event of the CheckBox2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            //Get the checkbox from sender object
            CheckBox chk = sender as CheckBox;
            //Get the selected row from checkbox container
            GridViewRow row = (GridViewRow)chk.NamingContainer;
            //Get the dropdownlist control from selected GridViewrow
            DropDownList drpdwctrl = row.FindControl("DropDownList1") as DropDownList;
            //Get the Radiobutton control from selected GridViewrow
            RadioButton rdpbtnctrl = row.FindControl("RadioButton1") as RadioButton;
            //Get the label control from selected GridViewrow
            Label lblctrl = row.FindControl("Label3") as Label;
            //Check if checkbox is checked or not
            if (chk.Checked)
            {
                //Check if Radiobutton control is checked or not
                if (rdpbtnctrl.Checked)
                {
                    //Assign the value to existing text in label control
                    lblctrl.Text = lblctrl.Text + " " + drpdwctrl.SelectedItem.Text;
                }
            }

        }

Change the ids of control as per your gridview

Rendered Output

EDIT:Added Rendred output demo

Hi kaushiklotus,

Thanks for your post.

Based on your requirement, I create a sample for you, you could refer to it and make some changes according to your specific requirements.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function () {
            $(":checkbox").change(function () {
                var ischecked = $(this).is(":checked");
                var rd = $(this).parent().siblings().find(":radio").is(":checked");

                if (ischecked && rd) {
                    var mes = $(this).parent().siblings().find("select").find("option:selected").val();
                    //alert(mes);
                    $(this).parent().siblings().find("span").html(mes);
                }
            });

            $(":radio").change(function () {
                var ischecked = $(this).is(":checked");
                var rd = $(this).parent().siblings().find(":checkbox").is(":checked");

                if (ischecked && rd) {
                    var mes = $(this).parent().siblings().find("select").find("option:selected").val();
                    //alert(mes);
                    $(this).parent().siblings().find("span").html(mes);
                }
            });

            $("select").change(function () {
                var mes = $(this).find("option:selected").val();
                var ischecked = $(this).parent().siblings().find(":checkbox").is(":checked");
                var rd = $(this).parent().siblings().find(":radio").is(":checked");

                if (ischecked && rd) {
                    $(this).parent().siblings().find("span").html(mes);
                }
            });
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="CheckBox1" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
                                DataTextField="Name" DataValueField="Name">
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:RadioButton ID="RadioButton1" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [ChartInfo]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html> 

In above sample code, I use some selectors and events, if you’d like to learn about these, you could check the following links.

If you have any question about my reply, please let me know freely.

Best Regards,

Fei Han

Thank you 

Hi kaushiklotus.

Have you tried my sample? your requirement is that checking the elements inside a gridview using javascript, does my sample not meet your requirement?

Best Regards,

Fei Han

[RESOLVED]how to append form for a checkbox in Gridivie within Accrodion

Hi,

I have a GridView inside a JQuery accordion panel. Each row of the GridView has a CheckBox with AutoPostabck enabled. The event is not firing I believe because as usual ASP.Net forms elements need to be appended to the form but I am not sure how to dot for
each checkbox in Gridview Row. How do i execute Jquery

  $('<%# CheckBox1.ClientID %>).parent().appendTo("form");

when every row is data bound?

Thanks

Hi mhariri,

Thanks for your post.

mhariri

I have a GridView inside a JQuery accordion panel. Each row of the GridView has a CheckBox with AutoPostabck enabled. The event is not firing

Firstly, I create a demo to reproduce your problem, the below code works fine on my side. So you compare your code with the following sample to find some differences.

<form id="form1" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
        <div>
            <asp:Accordion ID="Accordion1" runat="server">
                <Panes>
                    <asp:AccordionPane ID="AccordionPane1" runat="server">
                        <Header>
                            Item1
                        </Header>
                        <Content>
                            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged"/>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                                    <asp:BoundField DataField="Values" HeaderText="Values" SortExpression="Values" />
                                    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                                </Columns>
                            </asp:GridView>
                        </Content>
                    </asp:AccordionPane>
                </Panes>
            </asp:Accordion>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [ChartInfo]"></asp:SqlDataSource>
        </div>
</form> 
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
        {
            //bool ischecked = ((CheckBox)sender).Checked;
            string rows = ((GridView)AccordionPane1.ContentContainer.Controls[1]).Rows.Count.ToString();
        } 

Secondly, you could show us your complete code, it wil help us understand your problem and fix it.

If you have any question about my reply, please let me know.

Best Regards,

Fei Han

[RESOLVED]click on edit, show cancel link on this specified row only

I am clicking on edit link of a row . i Want to hide a column of Edit link & need to show the cancel link. how could i do that ?

Hi,

Not fully understood your requirement,but try out this prototype and see if this satisfies your requirement.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.cancel').hide();
            $('.edit').click(function () {
                $(this).hide();
                $(this).next().show();
            });
        });
    </script>
    <table>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
    </table>

Hi waqar1,
From your description, if you are using Gridview, you could put the Edit button into the ItemTemplate, and put the Cancel button into the EditItemTemplate. You could refer to the following code:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowEditing="OnRowEditing">
<Columns>
    <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
    <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
            <asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
        </EditItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

More details, please refer to the following links:

http://www.aspsnippets.com/Articles/Edit-GridView-using-BoundField-Column-in-ASPNet.aspx

http://www.aspsnippets.com/Articles/Insert-Update-Edit-Delete-record-in-GridView-using-SqlDataSource-in-ASPNet.aspx

if you are use a table as sangeeth2007 said, you could use the following code:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('.cancel').hide();
            $('.edit').click(function () {
                $(this).hide();
                $(this).next().show();
            });
            $('.cancel').click(function () {
                $(this).hide();
                $('.edit').show();
            });
        });
    </script>

  <table>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>
                <a href="#" class="edit">Edit</a>
                <a href="#" class="cancel">Cancel</a>
            </td>
            <td></td>
        </tr>
    </table>

If you have any other questions about my reply, please let me know freely.
Best Regards,
Dillion

[RESOLVED]Using the following notation, how do I get the value and text of a selected item?

Using the following notation with JQuery, how do I get the values and text of selected items?

$(‘select[id$=ddl1]‘)….

For example, I don’t get an error doing the following, but I don’t get anything returned.

var
strText= $(
‘select[id$=ddl1]‘
+
"option:selected").text();
alert(strText);

//$("#yourdropdownid option:selected").text();
$("#ddl1option:selected").text();

//for value
$("#ddl1option").val();

I know that works, but I am trying to make it work with the other notation such as this.

$(‘select[id$=ddl1]‘)….

One of the issues here is that when you are appending your "option:selected" section, you will need a space between it to denote that you are finding the selected options below that particular <select> element :

var yourText = $('select[id$=ddl1] option:selected').text();
var yourValue = $('select[id$=ddl1] option:selected').val();

I threw together a very basic example that can be seen here. Additionally, if your DropDownList supported multiple selection, you could handle the same basic logic but loop through the selected values
as well :

// Loop through the available selected elements
$('select[id$="ddl1"] option:selected').each(function(){
          var strText= $(this).text();
          var strValue = $(this).val(); 

          alert('Text : ' + strText);
          alert('Value : ' + strValue);
});

An additional example using multiple selection can be found here.

Hi,

If you really needs "ends with" try :

select[id$=ddl1]
option:selected

Currently you are using:

select[id$=ddl1]option:selected

that is the space is missing.

Remember, I am just trying to get the selected item text.

I had tried this:

var
yourText=  $(
‘select[id$=ddl1]
option:selected’
).text();

But I get an empty string as well for the answer.

JAYHAWKER

Remember, I am just trying to get the selected item text.

I had tried this:

var
yourText=  $(
‘select[id$=ddl1]
option:selected’
).text();

But I get an empty string as well for the answer.

That code should work just fine. Are you sure that the element that you have an element that is selected? My example demonstrates this same type of code and it works as expected. You might want to consider posting your rendered source if you continue to
encounter issues.

Hi jayhawker,

Thanks for your post.

jayhawker

Remember, I am just trying to get the selected item text.

I had tried this:

var
yourText=  $(
‘select[id$=ddl1]
option:selected’
).text();

But I get an empty string as well for the answer.

You could try the below sample to get the value of selected option.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function () {
            $("#ddl1").change(function () {
                var mes = $(this).find("option:selected").val();
                alert(mes);
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddl1" runat="server" DataSourceID="SqlDataSource1"
                DataTextField="Name" DataValueField="Name">
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [ChartInfo]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html> 

If you have any question about my reply, please let me know freely.

Best Regards,

Fei Han

[RESOLVED]How to apply css class to gridview selected row

I have this style as a test on my aspx page

  <style>
      .selectedRowStyle
{
    background-color: green;
}

  </style>

Then I have a gridview defined like this

                                    <asp:GridView ID="gvShop" runat="server" CssClass="table table-striped table-bordered table-condensed" AutoGenerateColumns="False" DataKeyNames="ItemID" DataSourceID="SqlDataSource1">
                                        <Columns>
                                            <asp:BoundField DataField="ItemName" HeaderText="Membership" SortExpression="ItemName" />
                                            <asp:BoundField DataField="ItemPrice" DataFormatString="{0:C}" HeaderText="ItemPrice" SortExpression="ItemPrice" />
                                        </Columns>

<SelectedRowStyle CssClass="selectedRowStyle" /> </asp:GridView>

Notice the SelectedRowStyle asks for the css style.

The first time I tried it I was delighted with such a simple solution. Then I found that it only works on alternate rows!

So is there a way to have this work on any row the user selects?

I know I could just set the background color in the SelectedRowStyle element of the gridview but that would defeat my purpose of having all styling entirely controlled by css that I can put into one file.

EDIT: Actually I just tried it with SelectedRowStyle and it still only works on alternate rows. What gives?

Are you sure that your ‘selectedRowStyle’ isn’t actually conflicting with your Alternating Row Styles (assumingly being applied by your table-striped CSS class)? You might try using the Developer Tools (F12) within your browser and inspecting one of your
"selected" rows to see all what styles are being applied to the elements.

Any additional code that you could provide (either markup or your actual CSS styles) might be useful.

Thanks for the tip. When I turned off bootstrap.css it worked fine. Doesn’t look too good though.

Here’s a section of that file I think includes the relevant classes

.table {
  width: 100%;
  max-width: 100%;
  margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
  padding: 8px;
  line-height: 1.42857143;
  vertical-align: top;
  border-top: 1px solid #dddddd;
}
.table > thead > tr > th {
  vertical-align: bottom;
  border-bottom: 2px solid #dddddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
  border-top: 0;
}
.table > tbody + tbody {
  border-top: 2px solid #dddddd;
}
.table .table {
  background-color: #ffffff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
  padding: 5px;
}
.table-bordered {
  border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
  border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
  border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
  background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
  background-color: #f5f5f5;
}
table col[class*="col-"] {
  position: static;
  float: none;
  display: table-column;
}
table td[class*="col-"],
table th[class*="col-"] {
  position: static;
  float: none;
  display: table-cell;

CSS issues like this can be tricky and this might actually be the result of some conflicting styles (which would explain why Bootstrap might be "fighting" with your existing code). You might want to tinker around with the order that you are loading
these particular CSS references as precendence is given to those that appear later.

For instance, if you have all of your styles within a file called "Site.css" and you load it AFTER "Bootstrap.css", it will override any styles that were contained in Bootstrap that target the same elements. Likewise, if you reversed these, Bootstrap would
override properties of your "Site.css" file.

If you are planning on using Bootstrap, I would let it handle the styling and just override some properties that you needed. I couldn’t recommend using the Developer Tools (F12) enough for situations like this in your browser. Using a browser like Google
Chrome, you would simply need to right-click on a specific element in your page and choose "Inspect Element" to see all of the styles that are being applied to it (and you can change them in real time).

Additionally, you might try making your "selected" style more specific to ensure it is targeted properly :

/* Ensure that any elements with the "selectedRowStyle" beneath the "#gvShop" element are green */
#gvShop .selectedRowStyle
{
    background: green;
}

or if you didn’t want to use an ID, you could apply all of your classes :

/* Ensure that any elements with the "selectedRowStyle" beneath the your table */
.table.table-striped.table-bordered.table-condensed .selectedRowStyle
{
    background: green;
}

The solution was to keep tinkering with the developer tools.

I did not spot the exact thing that was causing it but saved some time by swapping out the particular bootstrap theme for another that was very similar that didn’t cause the same problem.

[RESOLVED]Gridview Update whit radiobutton

Hi, 

I Have a gridview :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="picid" DataSourceID="SqlDataSource2">
                <Columns>
                    <asp:BoundField DataField="picid" HeaderText="picid" InsertVisible="False" ReadOnly="True" SortExpression="picid" />
                                <asp:TemplateField HeaderText="Command">
     <ItemTemplate>
          <asp:LinkButton ID="Button2" runat="server" CommandName="select" Text="select" CommandArgument='<%#Eval("picid")%>' />
         <asp:RadioButton CommandName="select1" groupname="abc" ID="RadioButton1" runat="server" Checked='<%# Eval("main1") %>' AutoPostBack="True" OnCheckedChanged="RadioButton1_CheckedChanged1" />
         &nbsp;
     </ItemTemplate>
 </asp:TemplateField>
                </Columns>

            </asp:GridView>

and:

        If e.CommandName = "select" Then
            TextBox4.Text = e.CommandArgument.ToString()


            For Each row As GridViewRow In GridView1.Rows

                Dim constr As String = ConfigurationManager.ConnectionStrings("starfairConnectionString").ConnectionString
                Dim con As New SqlConnection(constr)
                Dim cmd As New SqlCommand("firpicup1", con)
                cmd.CommandType = CommandType.StoredProcedure
                Dim RowIndex As Integer = Convert.ToInt32(e.CommandArgument)
                cmd.Parameters.Add(New SqlParameter("@picid", TextBox4.Text))
                Dim rb As RadioButton = DirectCast(row.FindControl("RadioButton1"), RadioButton)
                cmd.Parameters.Add(New SqlParameter("@main1", "1"))
                Dim dr As SqlDataReader
                con.Open()
                dr = cmd.ExecuteReader()
                GridView1.DataBind()
            Next
        End If

I want when radio button checked, current row "main1" field =1 and in the other rows"main1" field =0,

how to change the above code?

No one to help me?

hi,

You can’t use rowcommand event in radiobutton . and we also can’t use checkedchange event .Even if defind groupname of this radiobutton , but in different row the name in html code of this radiobutton is different .you can press F12 to observed the radiobutton’s
name .you will get such as the below :

<input id="GridView2_RadioButton1_0" type="radio" name="GridView2$ctl02$abc" value="RadioButton1" /><label for="GridView2_RadioButton1_0">check</label>

   <input id="GridView2_RadioButton1_1" type="radio" name="GridView2$ctl03$abc" value="RadioButton1" /><label for="GridView2_RadioButton1_1">check</label>

Because the name is different ,so the checkedchanged event can’t trigger .

to you purpose .I suggest use linkbutton or use checkbox .

Hope this helps

 

 

 

Thanks. For checkbox how i do?

hi,

This tutorial looks at how to add a column of check boxes to a GridView control to provide the user with an intuitive way of selecting multiple rows of the GridView.

http://www.asp.net/web-forms/tutorials/data-access/enhancing-the-gridview/adding-a-gridview-column-of-checkboxes-cs

if you need to change row value or something else by checkbox changed event  , you can use Jquery ajax  to trigger webmethod in webmethod .

http://stackoverflow.com/questions/348689/jquery-ajax-with-asp-net-webmethod-returning-entire-page

Hope this helps

[RESOLVED]My gridview is unable to update a new value. Any idea why? Has been 3 hours trying to figure this out!

Here’s my source code for updating:

protected void grdOrder_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //get selected row
        int selectedRow = e.RowIndex;

        //get order ID from data key
        int orderID = (int)grdOrder.DataKeys[selectedRow].Value;

        //get current grid view row
        GridViewRow row = (GridViewRow)grdOrder.Rows[selectedRow];

        //find text box for txtOrderQuantity
        TextBox quantity = (TextBox)row.FindControl("txtOrderQuantity");


        string strQuantity = quantity.Text;
        int intQuantity = 0;

        if (int.TryParse(strQuantity, out intQuantity))
        {
            updateOrderGridViewRecord(orderID, intQuantity);
        }
        else
        {
            lblOrderError.Text = "Invalid Quantity";

        }
    }


    private void updateOrderGridViewRecord(int orderID, int intQuantity)
    {
        String ConStr = ConfigurationManager.ConnectionStrings["GameConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(ConStr);

        string SQL = "UPDATE [order] SET quantity=@quantityValue WHERE orderID=@orderIDValue";

        SqlCommand cmd = new SqlCommand(SQL, con);
        cmd.Parameters.AddWithValue("@quantityValue", orderID);
        cmd.Parameters.AddWithValue("@orderIDValue", intQuantity);

        con.Open();

        int result = cmd.ExecuteNonQuery();

        if (result > 0)
        {
            lblOrderError.Text = "Record updated!";
        }
        else
        {
            lblOrderError.Text = "Update fail";
        }

        con.Close();


        //Cancel Edit Mode
        grdOrder.EditIndex = -1;
        bindOrderGridView();

    }



    private void bindOrderGridView()
    {
        String ConStr = ConfigurationManager.ConnectionStrings["GameConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(ConStr);

        try
        {
            string invalid = txtSearchOrder.Value;

            String SQL = null;

            if (invalid == "%")
            {
                SQL = "SELECT * FROM [order]";
            }
            else
            {
                SQL = "SELECT * FROM [order] WHERE orderID=@searchOrderID";
            }


            SqlCommand cmd = new SqlCommand(SQL, con);
            con.Open();

            cmd.Parameters.Add("@searchOrderID", SqlDbType.NVarChar, 50);
            cmd.Parameters["@searchOrderID"].Value = txtSearchOrder.Value;

            SqlDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            grdOrder.DataSource = dt;
            grdOrder.DataBind();
            lblOrderError.Text = "";

            reader.Close();
        }
        catch (SqlException ex)
        {
            lblOrderError.Text = "Error:" + ex.Message.ToString();
        }
        finally
        {
            con.Close();
        }
    }

Here’s the code for my gridview

                    <asp:GridView ID="grdOrder" runat="server" AutoGenerateColumns="False" 
                        DataKeyNames="orderID" onrowcancelingedit="grdOrder_RowCancelingEdit" 
                        onrowediting="grdOrder_RowEditing" onrowupdating="grdOrder_RowUpdating">
                        <Columns>
                            <asp:BoundField DataField="orderID" HeaderText="Order ID" 
                                SortExpression="orderID" ReadOnly="true"/>
                            <asp:BoundField DataField="username" HeaderText="Username" 
                                SortExpression="username" ReadOnly="true"/>
                            <asp:TemplateField HeaderText="Game Title" SortExpression="title">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlOrderTitle" runat="server" 
                                        DataSourceID="SqlDataSource1" DataTextField="title" DataValueField="title"></asp:DropDownList>
                                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                                        ConnectionString="<%$ ConnectionStrings:GameConnectionString %>" 
                                        SelectCommand="SELECT [title] FROM [games]"></asp:SqlDataSource>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblOrderTitle" runat="server" Text='<%# Bind("title") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Quantity" SortExpression="quantity">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtOrderQuantity" runat="server" Text='<%# Bind("quantity") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblOrderQuantity" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:CommandField ShowEditButton="True" />
                            <asp:CommandField ShowDeleteButton="True" />
                        </Columns>
                    </asp:GridView>

Any idea what’s going on?  For now, i’m trying to update only the quantity, but the code doesn’t seem to work.

Switch the values between thus parameters, you have given wrong value : cmd. Parameters . AddWithValue ( "@ quantityValue" , orderID); cmd. Parameters . AddWithValue ( "@ orderIDValue" , intQuantity);
You get it? You have set orderID parameter with quantity and set quantity parameter with orderID value. You should set orderID parameter with orderID value, quantity parameter with quantity value.

If your updation problem is not solved then  i suggest you to read the article

Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#

oned_gk

You get it? You have set orderID parameter with quantity and set quantity parameter with orderID value. You should set orderID parameter with orderID value, quantity parameter with quantity value.

Alright I’ve switched it.  The problem still persist; I still can’t update its new value.

SqlCommand cmd = new SqlCommand(SQL, con);
        cmd.Parameters.AddWithValue("@orderIDValue", orderID);
        cmd.Parameters.AddWithValue("@quantityValue", intQuantity);

Nevermind, I’ve solved it.  All I need to do is add this at the page-load event:

 if (Page.IsPostBack == false)
        {
            bindOrderGridView();
        }

[RESOLVED]How to update a value in gridview using DropDownList?

I have populated the list items using Sqldatasource from my database, but I’m not sure how do I use the selected item to update it?

Here’s what I have

<asp:TemplateField HeaderText="Game Title" SortExpression="title">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlOrderTitle" runat="server"
                                        DataSourceID="SqlDataSource1" DataTextField="title" DataValueField="title" SelectedValue='<%# Eval("title") %>'></asp:DropDownList>
                                    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                                        ConnectionString="<%$ ConnectionStrings:GameConnectionString %>"
                                        SelectCommand="SELECT [title] FROM [games]"></asp:SqlDataSource>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="lblOrderTitle" runat="server" Text='<%# Bind("title") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>

And here’s what I have currently

 protected void grdOrder_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //get selected row
        int selectedRow = e.RowIndex; 

        //get order ID from data key
        int orderID = (int)grdOrder.DataKeys[selectedRow].Value;

        //get current grid view row
        GridViewRow row = (GridViewRow)grdOrder.Rows[selectedRow];

        //find text box for txtOrderQuantity
        TextBox quantity = (TextBox)row.FindControl("txtOrderQuantity");
        

        string strQuantity = quantity.Text;
        double intQuantity = 0;
        //double intQuantity = Convert.ToInt32(quantity.Text);

        if (Double.TryParse(strQuantity, out intQuantity))
        {
            updateOrderGridViewRecord(orderID, intQuantity);
        }
        else
        {
            lblOrderError.Text = "Invalid quantity!";

        }
    }

I have an event called grdOrder_RowUpdating to update my quantity value from a textbox.  How do I do it if it’s a dropdownlist instead?

When using SqlDataSource no need code behind, simply bind it like you bind textbox, SelectedValue=’<%# Bind("title") % >’

[RESOLVED]Remove Duplicate Value In Datatable

I have datatable consider like below.

Item | Type | Price
A | A1 | 10.00
A | A2 | 15.00
A | A3 | 12.00
A | A4 | 13.00
B | B1 | 5.00
B | B2 | 7.00

How can I remove duplicate value in column Item to become like this?

Item | Type | Price
A | A1 | 10.00
  | A2 | 15.00
  | A3 | 12.00
  | A4 | 13.00
B | B1 | 5.00
  | B2 | 7.00

I add value to the datatable like this

Dim myData As DataTable = New DataTable()
myData.Columns.Add("Item")
myData.Columns.Add("Type")
myData.Columns.Add("Price")

strSQL = "SELECT Item,Type,Price FROM product" cmd = New SqlCommand(strSQL, DBConn) DBConn.Open() rd = cmd.ExecuteReader While rd.Read myData.Rows.Add(rd.Item("Item"), rd.Item("Type"), rd.Item("Price")) End While GridView1.DataSource = myData GridView1.DataBind()

Note
Before using datatable I try to used normal SQL Query and bind to SQLDataSource but the outcome is not what i expected.

SELECT  * FROM
 (SELECT Item,Type,Price,ROW_NUMBER() OVER (PARTITION BY Item ORDER BY Item) AS RowNumber FROM Product) AS newProduct
WHERE   newProduct.RowNumber = 1
Item | Type | Price
A | A1 | 10.00
B | B1 | 5.00
You could use this query instead datatable; SELECT item = (CASE WHEN item + type = (SELECT TOP 1 item + type FROM product WHERE item = a.item) THEN item ELSE ” END), type, price FROM product AS a