locked
GridView Control RRS feed

  • Question

  • User2028249543 posted

    Hi,

    How can I auto-populate a selected database record showing on GridView to the Textbox?

    For example, if I have a GridView that contains all data from the SQL database and select one record then this will directly auto-populate on the textboxes as shown below,

    Cust ID: <textbox1>

    Last Name: <textbox2>

    First Name: <textbox3>

    This is using ASP.NET, C#

    Please help. Thanks.

    Wednesday, July 6, 2011 1:46 AM

Answers

All replies

  • User-693248168 posted

    Try this.

    When you are selecting the Gridview row, try setting

    GridView1.EditIndex=GridView1.SelectedIndex.

    After this you have to rebind your gridview.

    Wednesday, July 6, 2011 1:49 AM
  • User-614386673 posted

    Try this 

        <div>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:Local %>" 
                SelectCommand="SELECT * FROM [Customer]"></asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                AutoGenerateEditButton="True" AutoGenerateSelectButton="True" 
                DataSourceID="SqlDataSource1" 
                onselectedindexchanged="GridView1_SelectedIndexChanged" ShowFooter="True">
                <Columns>
                    <asp:BoundField DataField="CustID" HeaderText="CustID" 
                        SortExpression="CustID" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" 
                        SortExpression="LastName" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                        SortExpression="FirstName" />
                </Columns>
            </asp:GridView>
        </div>
    
    
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridView1.EditIndex = GridView1.SelectedIndex;
        }

    Wednesday, July 6, 2011 3:07 AM
  • User2028249543 posted

    hi sasathy,

    thanks for the sample code as i've tried it the update button it won't work.

    what i want to have is, the gridview has the ability to auto-populate the information directly to my textbox entries when that record is selected.

    for example, we assume that there are 5 records on the gridview, if we select one of the record, the system will auto-populate the information directly to the textboxes like cust id, last name and firstname.

    if you have any idea about this on how it works that would be great.

    thanks.

    Wednesday, July 6, 2011 5:23 AM
  • User-614386673 posted

    you have the textboxes outside the gridview? or you want it as Edittemplate?

    Wednesday, July 6, 2011 6:34 AM
  • User2028249543 posted

    hi sasathy,

    thanks for your reply.

    yes you are correct, i believe i didn't explain it right, my apology.

    i have my textboxes outside the gridview data toolbox so whenever a user selects on one of the record on the gridview it will show off on the the textboxes.

    please help. thanks.

    Wednesday, July 6, 2011 7:22 AM
  • User-614386673 posted

    Try this.

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow selectedRow = GridView1.SelectedRow;
            tbCustID.Text = selectedRow.Cells[1].Text;
            tbLastName.Text = selectedRow.Cells[2].Text;
            tbFirstName.Text = selectedRow.Cells[3].Text;
        }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2011 11:20 AM
  • User2028249543 posted

    Hi sasathy,

    I've used your given code however it's not letting me show those records from the grid view to the text box.

    Is there anything I can do from the ASP.NET script apart from C#?

    Thanks.

    Wednesday, July 6, 2011 10:20 PM
  • User-614386673 posted

    Can you paste your code here so that i can debug. It will be great if you put both the ASP scripts and code here.

    Wednesday, July 6, 2011 11:25 PM
  • User2028249543 posted

    sure. here it is below,

    filename: default.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    </script>
    <title></title>
    <link href="../../../../resources/css/examples.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
            .icon-exclamation {
                padding-left: 25px !important;
                background: url(/icons/exclamation-png/ext.axd) no-repeat 3px 3px !important;
            }
            
            .icon-accept {
                padding-left: 25px !important;
                background: url(/icons/accept-png/ext.axd) no-repeat 3px 3px !important;
            }
        </style>

    </head>
    <body>
    <form id="form1" runat="server">
        Cust ID:<asp:TextBox ID="txtCustId" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        &nbsp;
        Last Name:<asp:TextBox ID="txtLname" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        &nbsp;
        First Name:<asp:TextBox ID="txtFname" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        
            <asp:Button ID="btn_insert" runat="server" Text="Insert Data" onclick="btn_insert_Click" />
            &nbsp;
            <asp:Button ID="btn_del" runat="server" Text="Delete Data" onclick="btn_del_Click"
            ValidationGroup="Management" CausesValidation="true" />
            &nbsp;&nbsp;
            <asp:Button ID="btn_update" runat="server" Text="Update Data" onclick="btn_update_Click" />
            &nbsp;
            <asp:Button ID="btn_clear" runat="server" Text="Clear All" onclick="btn_clear_Click" />
            <br />
        <%--<asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
            ProviderName="<%$ ConnectionStrings:ConnectionString2.ProviderName %>"
            SelectCommand="SELECT * FROM [tblData]"></asp:SqlDataSource>--%>
        
        
        <div>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CustId"
                DataSourceID="SqlDataSourceCust"
                onselectedindexchanged="GridView1_SelectedIndexChanged"
                CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField DataField="CustId" HeaderText="CustId" ReadOnly="True"
                        SortExpression="CustId" />
                    <asp:BoundField DataField="Lastname" HeaderText="Lastname"
                        SortExpression="Lastname" />
                    <asp:BoundField DataField="Firstname" HeaderText="Firstname"
                        SortExpression="Firstname" />
                </Columns>
                <EditRowStyle BackColor="#2461BF" />
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#EFF3FB" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#F5F7FB" />
                <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                <SortedDescendingCellStyle BackColor="#E9EBEF" />
                <SortedDescendingHeaderStyle BackColor="#4870BE" />
            </asp:GridView>
            <br />

            <asp:SqlDataSource ID="SqlDataSourceCust" runat="server"
                ConnectionString="<%$ ConnectionStrings:ConnectionStringCustDB %>"
                ProviderName="<%$ ConnectionStrings:ConnectionStringCustDB.ProviderName %>"
                SelectCommand="SELECT * FROM [CustTBL]"></asp:SqlDataSource>
            <br />
            <asp:Label ID="msgeLbl" runat="server" ForeColor="#0066FF"></asp:Label>
        </div>

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

    filename: default.aspx.cs

     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
            {
                GridViewRow selectedRow = GridView1.SelectedRow;
                msgeLbl.Text = "You selected " + selectedRow.Cells[1].Text + ".";
                txtCustId.Text = selectedRow.Cells[0].Text;
                txtLname.Text = selectedRow.Cells[1].Text;
                txtFname.Text = selectedRow.Cells[2].Text;
                GridView1.EditIndex = GridView1.SelectedIndex;

            }

    Please help. Thanks.

    Wednesday, July 6, 2011 11:58 PM
  • User-614386673 posted

    Please try the below Code.

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    
    public partial class Default2 : System.Web.UI.Page
    {
        private List<SqlParameter> insertParameters = new List<SqlParameter>();
        protected void Page_Load(object sender, EventArgs e)
        {
            
    
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow selectedRow = GridView1.SelectedRow;
            msgeLbl.Text = "You selected " + selectedRow.Cells[1].Text + ".";
            txtCustId.Text = selectedRow.Cells[1].Text;
            txtLname.Text = selectedRow.Cells[2].Text;
            txtFname.Text = selectedRow.Cells[3].Text;
        }
        protected bool updateParameters()
        {
            if (txtCustId.Text == "")
                return false;
            else
            {
                SqlParameter fName = new SqlParameter("@FirstName", SqlDbType.VarChar, 30);
                fName.Direction = ParameterDirection.Input;
                fName.Value = txtFname.Text;
                insertParameters.Add(fName);
                SqlParameter lName = new SqlParameter("@LastName", SqlDbType.VarChar, 30);
                lName.Direction = ParameterDirection.Input;
                lName.Value = txtLname.Text;
                insertParameters.Add(lName);
                SqlParameter custId = new SqlParameter("@CustId", SqlDbType.VarChar, 30);
                custId.Direction = ParameterDirection.Input;
                custId.Value = txtCustId.Text;
                insertParameters.Add(custId);
                return true;
            }
        }
        protected void btn_insert_Click(object sender, EventArgs e)
        {
            if (updateParameters())
            {
                SqlDataSourceCust.Insert();
                GridView1.DataBind();
            }
        }
        protected void btn_del_Click(object sender, EventArgs e)
        {
            if (updateParameters())
            {
                SqlDataSourceCust.Delete();
                GridView1.DataBind();
            }
        }
        protected void btn_update_Click(object sender, EventArgs e)
        {
            if (updateParameters())
            {
                SqlDataSourceCust.Update();
                GridView1.DataBind();
            }
        }
        protected void btn_clear_Click(object sender, EventArgs e)
        {
            txtCustId.Text = "";
            txtFname.Text= "";
            txtLname.Text = "";
    
        }
        protected void SqlDataSourceCust_Updating(object sender, SqlDataSourceCommandEventArgs e)
        {
            e.Command.Parameters.Clear();
            foreach (SqlParameter p in insertParameters)
                e.Command.Parameters.Add(p);
        }
        protected void SqlDataSourceCust_Inserting(object sender, SqlDataSourceCommandEventArgs e)
        {
            e.Command.Parameters.Clear();
            foreach (SqlParameter p in insertParameters)
                e.Command.Parameters.Add(p);
        }
        protected void SqlDataSourceCust_Deleting(object sender, SqlDataSourceCommandEventArgs e)
        {
            e.Command.Parameters.Clear();
            foreach (SqlParameter p in insertParameters)
                e.Command.Parameters.Add(p);
        }
    }
    
    
    
    
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
    <script language="javascript" type="text/javascript">
    
    </script>
    <title></title>
    <link href="../../../../resources/css/examples.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
            .icon-exclamation {
                padding-left: 25px !important;
                background: url(/icons/exclamation-png/ext.axd) no-repeat 3px 3px !important;
            }
            
            .icon-accept {
                padding-left: 25px !important;
                background: url(/icons/accept-png/ext.axd) no-repeat 3px 3px !important;
            }
        </style>
    
    </head>
    <body>
    <form id="form1" runat="server">
        Cust ID:<asp:TextBox ID="txtCustId" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        &nbsp;
        Last Name:<asp:TextBox ID="txtLname" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        &nbsp;
        First Name:<asp:TextBox ID="txtFname" runat="server" style="text-align: left" Width="127px"></asp:TextBox>
        
            <asp:Button ID="btn_insert" runat="server" Text="Insert Data" onclick="btn_insert_Click" />
            &nbsp;
            <asp:Button ID="btn_del" runat="server" Text="Delete Data" onclick="btn_del_Click" 
            ValidationGroup="Management" CausesValidation="true" />
            &nbsp;&nbsp;
            <asp:Button ID="btn_update" runat="server" Text="Update Data" onclick="btn_update_Click" />
            &nbsp;
            <asp:Button ID="btn_clear" runat="server" Text="Clear All" onclick="btn_clear_Click" />
            <br />
        <%--<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" 
            ProviderName="<%$ ConnectionStrings:ConnectionString2.ProviderName %>" 
            SelectCommand="SELECT * FROM [tblData]"></asp:SqlDataSource>--%>
        
        
        <div>
        
            
                <asp:SqlDataSource ID="SqlDataSourceCust" runat="server" 
                ConnectionString="<%$ ConnectionStrings:Local %>" 
                ProviderName="<%$ ConnectionStrings:Local.ProviderName %>" 
                SelectCommand="SELECT * FROM [Customer]"
                
                    UpdateCommand="UPDATE Customer SET LastName =@LastName, FirstName =@FirstName WHERE CustId=@CustId" 
                    InsertCommand="INSERT INTO Customer values(@CustId, @LastName, @FirstName)" 
                    DeleteCommand = "DELETE FROM Customer WHERE CustId= @CustId"
                    ondeleting="SqlDataSourceCust_Deleting" 
                    oninserting="SqlDataSourceCust_Inserting" 
                    onupdating="SqlDataSourceCust_Updating"></asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                AllowSorting="True" AutoGenerateColumns="False" 
                DataSourceID="SqlDataSourceCust" 
                onselectedindexchanged="GridView1_SelectedIndexChanged" 
                CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" 
                    AutoGenerateSelectButton="True">
                            <Columns>
                    <asp:BoundField DataField="CustID" HeaderText="CustID" 
                        SortExpression="CustID" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" 
                        SortExpression="LastName" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                        SortExpression="FirstName" />
                </Columns>
                <AlternatingRowStyle BackColor="White" />
                <EditRowStyle BackColor="#2461BF" />
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#EFF3FB" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    
            </asp:GridView>
            <br />
    
    
            <br />
            <asp:Label ID="msgeLbl" runat="server" ForeColor="#0066FF"></asp:Label>
        </div>
    
    </form>
           
    </body>
    </html>
    Thursday, July 7, 2011 2:18 AM
  • User2028249543 posted

    hi sasathy,

    i've read your code and i have not fully understood some.

    with this statement : private List<SqlParameter> insertParameters = new List<SqlParameter>();

    you mean you would like place an insert sql command?

    i already have made an insert, delete and update sql query.

    refer to:

    //protected void btn_insert_Click(object sender, EventArgs e)
            //{
            //    SqlConnection conn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=CustDB");
            //    SqlCommand cmd = new SqlCommand();
            //    conn.Open();

            //    cmd = new SqlCommand("INSERT INTO custTBL VALUES('" + txtCustId.Text + "','" + txtLname.Text + "','" + txtFname.Text + "')", conn);
            //    cmd.ExecuteNonQuery();
            //}
            //protected void btn_del_Click(object sender, EventArgs e)
            //{

            //    SqlConnection conn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=CustDB");
            //    SqlCommand command = new SqlCommand();
            //    conn.Open();

            //    command = new SqlCommand("DELETE FROM custTBL WHERE CustId='" + txtCustId.Text + "'", conn);
            //    command.ExecuteNonQuery();
            //    Response.Write("Data Deleted Successfully From Database.");
                
               
            //}
            //protected void btn_update_Click(object sender, EventArgs e)
            //{
            //    SqlConnection conn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=CustDB");
            //    SqlCommand command = new SqlCommand();
            //    conn.Open();

            //    command = new SqlCommand("UPDATE custTBL SET Lastname='" + txtLname.Text + "'" + ", Firstname='" + txtFname.Text + "' WHERE CustId='" + txtCustId.Text + "'", conn);
            //    command.ExecuteNonQuery();          
            //    // user postback property to autoupdate the grid view data
                
            //}

    kindly assist. thanks.



    Thursday, July 7, 2011 2:36 AM
  • User3866881 posted

    Hi,

    How can I auto-populate a selected database record showing on GridView to the Textbox?

    For example, if I have a GridView that contains all data from the SQL database and select one record then this will directly auto-populate on the textboxes as shown below,

    Cust ID: <textbox1>

    Last Name: <textbox2>

    First Name: <textbox3>

    Hello:)

    I think a better way is to use a DetailsView or FormView to bind with the same db. For GridView, it's only used for viewing; For DetailsView, it's used for editing, inserting as well as deleting. So you should convert the EditTemplate of the DetailsView into Template Field mode, and handle Inserted, Deleted or Updated event to write——

    GridView1.DataBind()

    To synchronize the data contents binded to the GridView.

    Once I did a sample, this is related to your issue meaning when you click a record from GridView, a FormView is pop up for you to edit with.

    If you are interested in that, I'd like to share the sample for you, Please send me a private message through the forum, with your email address as well as your URL of this post.

    Thx again.

    Thursday, July 7, 2011 9:42 PM
  • User2028249543 posted

    Hi Decker Dong,

    Yes I am interested in your idea regarding clicking a record from gridview thus a formview will pop up for editing or may include deleting, searching as well if possible.

    My e-mail is sheen.buhay@gmail.com.

    Looking forward for that idea. Thanks.

    Friday, July 8, 2011 1:58 AM
  • User3866881 posted

    Hello again:)

    It seems that your Google mail doesn't reconigze mine and reguard it as a junk email……

    Would you mind offering me a Yahoo or hotmail?

    PS:You'd better send me private message, for privacy will be exposed to the public....

    :)

    Friday, July 8, 2011 2:01 AM
  • User2028249543 posted

    Sure, my hotmail account is sheen.buhay@hotmail.com

    Looking forward to your resolution of my issue.

    Thanks.

    Tuesday, July 12, 2011 9:47 PM
  • User3866881 posted

    Hello:)

    I've submitted this sample to CodeFX, and you can download at:http://download.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=1code&DownloadId=201858&FileTime=129402464777130000&Build=17950

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 12, 2011 9:51 PM
  • User2028249543 posted

    Thanks sasathy. It works now.

    Tuesday, October 4, 2011 9:32 PM
  • User-1249419835 posted

    Could you please send me that code. I think the link no longer exists. My email is ylsvani@hotmail.com

    Thursday, December 15, 2011 9:20 AM
  • User3866881 posted

    Could you please send me that code. I think the link no longer exists. My email is ylsvani@hotmail.com

    I've submitted this sample to CodeFX, and you can download at:http://download.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=1code&DownloadId=201858&FileTime=129402464777130000&Build=17950

    Thursday, December 15, 2011 8:14 PM