Solved

GridView select row

Posted on 2013-06-19
7
444 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now