Solved

GridView select row

Posted on 2013-06-19
7
451 Views
Last Modified: 2013-06-19
Hi,

Im trying to change the value of lblXVal label control by changing the value in the textbox1 control (by firing textbox_changed event). When I change the value in the textbox its changes values in all lblXval controls in the grid instead of changing the lblXval for the current row where I changed the TextBox1 value.

		  <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="False" BackColor="White"
			BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
			GridLines="Vertical" OnRowDeleting="Delete" DataKeyNames="id" Width="682px">
			<AlternatingRowStyle BackColor="#CCCCCC" />
			<Columns>
			   <asp:TemplateField HeaderText="X" SortExpression="xval">
				 <ItemTemplate>
				    <asp:Label ID="lblXVal" runat="server" Text='<%# Bind("xval") %>'></asp:Label>
				 </ItemTemplate>
			   </asp:TemplateField>

			   <asp:TemplateField HeaderText="Scale">
				 <ItemTemplate>
				    <asp:TextBox ID="TextBox1" runat="server" Text="1" AutoPostBack="true" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
				 </ItemTemplate>
			   </asp:TemplateField>
...

code
 protected void TextBox2_TextChanged (object sender, EventArgs e)
   {

	 for (int count = 0 ; count < gvFiles.Rows.Count ; count++)
	 {
	    string x = ((Label)gvFiles.Rows[count].FindControl ("lblXVal")).Text;
	    string s = ((TextBox)gvFiles.Rows[count].FindControl ("TextBox1")).Text;

	    Label t = ((Label)gvFiles.Rows[count].FindControl ("lblXVal"));

	    t.Text = (Convert.ToDouble (x) * Convert.ToDouble (s)).ToString ();

	 }

}

Open in new window


How can I fix the the problem?


Ayha
0
Comment
Question by:ayha1999
  • 4
  • 2
7 Comments
 
LVL 18

Expert Comment

by:Cluskitt
ID: 39259037
You're looping all rows. Instead of using for, just run it once and use e.RowIndex as the row number.
0
 
LVL 7

Author Comment

by:ayha1999
ID: 39259185
how can I RowIndex? please give me the code.

Thanks
0
 
LVL 12

Expert Comment

by:jitendra patil
ID: 39259187
Hi ayha1999

you need to make some changes in aspx code as below:

1. add a javascript in the head section of your page
<script type="text/javascript" language="javascript">

        function DoPostBackWithRowIndex(rowIndex){
            if (document.getElementById('<%=HDVal.ClientID%>') != null) {
                document.getElementById('<%=HDVal.ClientID%>').value = rowIndex;
            }
            return true;
        }
    </script>
2.add a hidden field above your grid view as
<asp:HiddenField ID="HDVal" runat="server" />

3. Now add a row databound event to your gridview and do the code as follows:
 protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox TxtMarks = (TextBox)e.Row.FindControl("TextBox1");
                TxtMarks.Attributes.Add("onkeydown", "javascript:return DoPostBackWithRowIndex('" + e.Row.RowIndex + "');");
            }
        }
4 .Now modify your Textchanged event as below
protected void TextBox2_TextChanged(object sender, EventArgs e)
        {
            if (HDVal.Value.Trim().Length == 0)
            {
                return;
            }
            else
            {
                int Rowindex= Convert.ToInt32(HDVal.Value);    
                string x = ((Label)gvFiles.Rows[Convert.ToInt16(Rowindex)].FindControl("lblXVal")).Text;
                string s = ((TextBox)gvFiles.Rows[Rowindex].FindControl("TextBox1")).Text;

                Label t = ((Label)gvFiles.Rows[Rowindex].FindControl("lblXVal"));
                t.Text = (Convert.ToDouble(x) * Convert.ToDouble(s)).ToString();
            }
        }
and it will work as expected.

hope this helps.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 7

Author Comment

by:ayha1999
ID: 39259263
Hi patil786,

I tried followed you code exacty, it is firing but not changing the value of lblXVal.

Please check.

Thanks
0
 
LVL 12

Accepted Solution

by:
jitendra patil earned 500 total points
ID: 39259476
it is working here i have tested the code  let me give you  complete code for the same.

.aspx code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">

        function DoPostBackWithRowIndex(rowIndex){
            if (document.getElementById('<%=HDVal.ClientID%>') != null) {
                document.getElementById('<%=HDVal.ClientID%>').value = rowIndex;
            }
            return true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
<asp:HiddenField ID="HDVal" runat="server" />
                    <asp:GridView ID="gvFiles" runat="server" 
        AutoGenerateColumns="False" BackColor="White"
			BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black"
			GridLines="Vertical"  DataKeyNames="eno" Width="682px" 
         onrowdatabound="gvFiles_RowDataBound">
			<AlternatingRowStyle BackColor="#CCCCCC" />
			<Columns>
			   <asp:TemplateField HeaderText="X" SortExpression="xval">
				 <ItemTemplate>
				    <asp:Label ID="lblXVal" runat="server" Text='<%# Bind("sal") %>'></asp:Label>
				 </ItemTemplate>
			   </asp:TemplateField>

			   <asp:TemplateField HeaderText="Scale">
				 <ItemTemplate>
				    <asp:TextBox ID="TextBox1" runat="server" Text="1" AutoPostBack="true" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
				 </ItemTemplate>
			   </asp:TemplateField>

               </Columns>
               </asp:GridView>

</form>
</body>
</html>

Open in new window

.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace TestWebApplication
{
    public partial class WebForm5 : System.Web.UI.Page
    {
	 protected void Page_Load(object sender, EventArgs e)
        	{

            if (!Page.IsPostBack)
            {
                filldatagrid();
            }


        }
        public void filldatagrid()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("eno");
            dt.Columns.Add("empname");
            dt.Columns.Add("sal");


            DataRow DR = dt.NewRow();
            DR["eno"] = "1";
            DR["empname"] = "Patil";
            DR["sal"] = "500";
            dt.Rows.Add(DR);

            DataRow DR1 = dt.NewRow();
            DR1["eno"] = "2";
            DR1["empname"] = "Manish";
            DR1["sal"] = "100";
            dt.Rows.Add(DR1);


            DataRow DR2 = dt.NewRow();
            DR2["eno"] = "3";
            DR2["empname"] = "Shirish";
            DR2["sal"] = "200";
            dt.Rows.Add(DR2);


            gvFiles.DataSource = dt;
            gvFiles.DataBind();

        }

 protected void TextBox2_TextChanged(object sender, EventArgs e)
        {
            if (HDVal.Value.Trim().Length == 0)
            {
                return;
            }
            else
            {
                int Rowindex= Convert.ToInt32(HDVal.Value);    
                string x = ((Label)gvFiles.Rows[Convert.ToInt16(Rowindex)].FindControl("lblXVal")).Text;
                string s = ((TextBox)gvFiles.Rows[Rowindex].FindControl("TextBox1")).Text;

                Label t = ((Label)gvFiles.Rows[Rowindex].FindControl("lblXVal"));
                t.Text = (Convert.ToDouble(x) * Convert.ToDouble(s)).ToString();
            }
        }

 protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox TxtMarks = (TextBox)e.Row.FindControl("TextBox1");
                TxtMarks.Attributes.Add("onkeydown", "javascript:return DoPostBackWithRowIndex('" + e.Row.RowIndex + "');");
            }
        }
}
}

Open in new window


now the above code is tested and its working fine here without any problem.

Hope this helps.
0
 
LVL 7

Author Closing Comment

by:ayha1999
ID: 39259606
Thank you so much.

ayha
0
 
LVL 7

Author Comment

by:ayha1999
ID: 39260049
Hi patil,

Could you please have look the following question?

http://www.experts-exchange.com/Security/IDS/Q_28161806.html

Thanks

ayha
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question