Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using c#/asp.net, how do I populate the textboxes in the form with the values in the datagrid when a value in a column, which is a link button is clicked

Posted on 2009-05-07
14
Medium Priority
?
2,040 Views
Last Modified: 2012-05-06
Hi!

I have a datagrid with 7 columns.It is a read-only grid.
The 1st column has the value of the primar key in a table.
The 2nd column has a link.(I've used link button for that)
When the link in the 2nd column is clicked, a panel should appear below the grid with 7 textboxes, populated with the values in the 7 columns. The 1st textbox cannot be edited.

The other textboxes can be edited.
Could you please let me know how this can be done in asp.net/c# ASAP.
Can I get the logic/code for this?
it's very, very urgent.
0
Comment
Question by:amukta
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
14 Comments
 
LVL 12

Expert Comment

by:wht1986
ID: 24332645
Here's the easiest way I can think of.  Make the LinkButton of the grid have a CommandName of "Select"
Below the grid you have a FormView with Edit set as the default view

The Data source for the grid is set to something like
Select * from MyTable

The data source for the formview is set to something like
Select * from MyTable where PrimaryKey=@PrimaryKey
and you set the bind of the parameter to the selected value of the grid.

Then every time the grid selects a row, the data for that row is in the formview below it
<form id="form1" runat="server">
 
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
    AutoGenerateColumns="False" DataKeyNames="FacilityID" 
    DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="FacilityID" HeaderText="FacilityID" 
            InsertVisible="False" ReadOnly="True" SortExpression="FacilityID" />
        <asp:ButtonField CommandName="Select" DataTextField="FacilityName" 
            HeaderText="Facility Name" SortExpression="FacilityName" Text="Button" />
        <asp:CheckBoxField DataField="Trouble" HeaderText="Trouble" 
            SortExpression="Trouble" />
    </Columns>
</asp:GridView>
<asp:FormView ID="FormView1" runat="server" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" DataKeyNames="FacilityID" DataSourceID="SqlDataSource2" DefaultMode="Edit">
    <EditItemTemplate>
        FacilityID:
        <asp:Label ID="FacilityIDLabel1" runat="server" 
            Text='<%# Eval("FacilityID") %>' />
        <br />
        FacilityName:
        <asp:TextBox ID="FacilityNameTextBox" runat="server" 
            Text='<%# Bind("FacilityName") %>' />
        <br />
        Trouble:
        <asp:CheckBox ID="TroubleCheckBox" runat="server" 
            Checked='<%# Bind("Trouble") %>' />
        <br />
        <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
            CommandName="Update" Text="Update" />
        &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
            CausesValidation="False" CommandName="Cancel" Text="Cancel" />
    </EditItemTemplate>
</asp:FormView>
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:Expert ExchangeConnectionString %>" 
    SelectCommand="SELECT * FROM [Facilities]">
</asp:SqlDataSource>
 
<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
    ConnectionString="<%$ ConnectionStrings:Expert ExchangeConnectionString %>" 
    
    SelectCommand="SELECT * FROM [Facilities] WHERE ([FacilityID] = @FacilityID)" 
    UpdateCommand="UPDATE [Facilities] SET [FacilityName] = @FacilityName, [Trouble] = @Trouble WHERE [FacilityID] = @FacilityID">
    <SelectParameters>
        <asp:ControlParameter ControlID="GridView1" Name="FacilityID" PropertyName="SelectedValue" Type="Int32" />
    </SelectParameters>
    <UpdateParameters>
        <asp:Parameter Name="FacilityName" Type="String" />
        <asp:Parameter Name="Trouble" Type="Boolean" />
        <asp:Parameter Name="FacilityID" Type="Int32" />
    </UpdateParameters>
</asp:SqlDataSource>
 
</form>

Open in new window

0
 
LVL 12

Expert Comment

by:wht1986
ID: 24332649
If you give me your table definition, (column names and data types), I can give you a working example in no time.
0
 
LVL 3

Expert Comment

by:DreamsTech
ID: 24333110
You dont requrie to hit the database again ,to improve ur perfomance u can populate these values taking from grid only:

1> Create a Pannel ,place it below the grid and make it hidden ,place all the controls all your 7 textboxes in the panel.
2> On the Link Click Event ,fetch the values of 7 fields from the grid and populate the textboxes in the pannel
3> Make the Pannel viisble
4> You can set ur prefences that which boxes shud be read only.

better to use Ajax" ModalPopupExtender" to give a professional touch.
www.asp.net/ajax/ajaxcontroltoolkit/samples/modalpopup/modalpopup.aspx 
0
Simplify Your Workload with One Tool

How do you combat today’s intelligent hacker while managing multiple domains and platforms? By simplifying your workload with one tool. With Lunarpages hosting through Plesk Onyx, you can:

Automate SSL generation and installation with two clicks
Experience total server control

 
LVL 13

Expert Comment

by:drypz
ID: 24333181
Hi! Here's a sample code.
.cs file
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Panel1.Attributes.Add("style", "visibility: hidden");
 
                GridView1.DataSource = GetDataTable().DefaultView;
                GridView1.DataBind();
            }
 
        }
 
 
        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("col1", typeof(int));
            dt.Columns.Add("col2", typeof(string));
            dt.Columns.Add("col3", typeof(string));
            dt.Columns.Add("col4", typeof(string));
            dt.Columns.Add("col5", typeof(string));
            dt.Columns.Add("col6", typeof(string));
            dt.Columns.Add("col7", typeof(string));
 
            //add rows
            DataRow newRow = dt.NewRow();
            newRow["col1"] = 1;
            newRow["col2"] = "link1";
            newRow["col3"] = "value1";
            newRow["col4"] = "value2"; ;
            newRow["col5"] = "value3"; ;
            newRow["col6"] = "value4"; ;
            newRow["col7"] = "value5"; ;
            
            dt.Rows.Add(newRow);
 
            newRow = dt.NewRow();
            newRow["col1"] = 2;
            newRow["col2"] = "link2";
            newRow["col3"] = "value1";
            newRow["col4"] = "value2"; ;
            newRow["col5"] = "value3"; ;
            newRow["col6"] = "value4"; ;
            newRow["col7"] = "value5"; ;
 
            dt.Rows.Add(newRow);
 
            return dt;
        }
 
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)    
            {
                e.Row.Cells[1].Attributes.Add("style", "cursor:hand; color:blue");
                e.Row.Cells[1].Attributes.Add("onclick", 
                    "DisplayPanel('" + e.Row.RowIndex +"');");
            }
        }
 
.aspx file
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">
 
        function DisplayPanel(int) 
        {
            var grid = document.getElementById('GridView1');
            var rowIndex = new Number(int);
            var pnl = document.getElementById('Panel1');
            var txt1 = document.getElementById('TextBox1');
            var txt2 = document.getElementById('TextBox2');
            var txt3 = document.getElementById('TextBox3');
            var txt4 = document.getElementById('TextBox4');
            var txt5 = document.getElementById('TextBox5');
            var txt6 = document.getElementById('TextBox6');
            var txt7 = document.getElementById('TextBox7');
 
            if (rowIndex > -1) 
            {
 
                pnl.style.visibility = "visible";
 
                for (var i = 0; i <= grid.rows.length - 1; i++) {
 
                    if (rowIndex == i) 
                    {
                        txt1.value = grid.rows[i + 1].cells[0].innerText;
                        txt2.value = grid.rows[i + 1].cells[1].innerText;
                        txt3.value = grid.rows[i + 1].cells[2].innerText;
                        txt4.value = grid.rows[i + 1].cells[3].innerText;
                        txt5.value = grid.rows[i + 1].cells[4].innerText;
                        txt6.value = grid.rows[i + 1].cells[5].innerText;
                        txt7.value = grid.rows[i + 1].cells[6].innerText;
                    }
                }
            }
        
        }
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
            onrowdatabound="GridView1_RowDataBound"> 
        </asp:GridView>
    </div>
    <div style="line-height: 20px; height: 20px;"></div>
    <div>
        <asp:Panel ID="Panel1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server" Width="100px" ReadOnly="True"></asp:TextBox>
            
            <asp:TextBox ID="TextBox2" runat="server" Width="100px"></asp:TextBox>
            <asp:TextBox ID="TextBox3" runat="server" Width="100px"></asp:TextBox>
            <asp:TextBox ID="TextBox4" runat="server" Width="100px"></asp:TextBox>
            <asp:TextBox ID="TextBox5" runat="server" Width="100px"></asp:TextBox>
            <asp:TextBox ID="TextBox6" runat="server" Width="100px"></asp:TextBox>
            <asp:TextBox ID="TextBox7" runat="server" Width="100px"></asp:TextBox>
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Open in new window

0
 

Author Comment

by:amukta
ID: 24340138
Hi! Drypz,

Is there anyway that this can be done in c#, without the javascript.
Please let me know.

Thanks in advance!
0
 

Author Comment

by:amukta
ID: 24340459
Is there anyway that it can be done using the datagrid selected index changed event?
if so, how?

Please do let me know.
0
 

Author Comment

by:amukta
ID: 24341243
Hi! wht1986,

I cannot use the form view. I need to use a panel for that.
Below the grid, there is an add button..it's a regular button, not a command button.
When I click on the add button, the textboxes have to be blank,
When I click on the link button...2nd column of the grid, the text boxes in the panel have to be populated with the values in the grid.

Is there anyway that it can be done.....if so, in which event and how....could you please get me the logic.

Thanks in advance!

0
 

Author Comment

by:amukta
ID: 24341248
HI! DreamsTech,

I cannot use ajax.

Thanks
0
 

Author Comment

by:amukta
ID: 24341252
HI! DreamsTech,

I cannot use ajax. The reg. onclick event does not work.

Thanks
0
 
LVL 12

Accepted Solution

by:
wht1986 earned 2000 total points
ID: 24341768
You can use a gridview but not a formview? odd requirement, but alas i was bored so here is code for a gridview that has an panel below it that is used to add and edit the data.  The picture below is the database table definition.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="AddButton" runat="server" Text="Add New Record" onclick="AddButton_Click" />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="DataID" onrowcommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField DataField="DataID"  HeaderText="DataID"  />
            <asp:ButtonField DataTextField="Column1" CommandName="MyCommand" HeaderText="Column1" />
            <asp:BoundField DataField="Column2" HeaderText="Column2" />
            <asp:BoundField DataField="Column3" HeaderText="Column3" />
            <asp:BoundField DataField="Column4" HeaderText="Column4" />
            <asp:BoundField DataField="Column5" HeaderText="Column5" />
            <asp:BoundField DataField="Column6" HeaderText="Column6" />
        </Columns>
    </asp:GridView>
    <asp:Panel ID="Panel1" runat="server" Visible="False" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px">
        <table cellpadding="4" cellspacing="0">
            <tr>
                <td>Data ID:</td>
                <td><asp:TextBox ID="TextBox1" runat="server" Enabled="False"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 1:</td>
                <td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 2:</td>
                <td><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 3:</td>
                <td><asp:TextBox ID="TextBox4" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 4:</td>
                <td><asp:TextBox ID="TextBox5" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 5:</td>
                <td><asp:TextBox ID="TextBox6" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Column 6:</td>
                <td><asp:TextBox ID="TextBox7" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="InsertButton" runat="server" Text="Insert" onclick="InsertButton_Click" />
                    <asp:Button ID="UpdateButton" runat="server" Text="Update" onclick="UpdateButton_Click" />
                    <asp:Button ID="CancelButton" runat="server" Text="Cancel" onclick="CancelButton_Click" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    </form>
</body>
</html>
 
======================================================
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
 
public partial class _Default : System.Web.UI.Page
{
 
    // return all rows
    private DataTable GetDataTable()
    {
        DataTable table = new DataTable();
 
        string connStr = ConfigurationManager.ConnectionStrings["Expert ExchangeConnectionString"].ConnectionString;
 
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlDataAdapter adpt = new SqlDataAdapter("Select * from TestData", conn))
            {
                adpt.Fill(table);
            }
        }
        return table;
    }
 
    // return a single row
    private DataRow GetRow(int dataId)
    {
        DataTable table = new DataTable();
 
        string connStr = ConfigurationManager.ConnectionStrings["Expert ExchangeConnectionString"].ConnectionString;
 
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlDataAdapter adpt = new SqlDataAdapter("Select * from TestData where DataID = @DataID", conn))
            {
                adpt.SelectCommand.Parameters.AddWithValue("@DataID", dataId);
                adpt.Fill(table);
            }
        }
        return table.Rows[0];
    }
 
    private void AddRow(string col1, string col2, string col3, string col4, string col5, string col6)
    {
        string connStr = ConfigurationManager.ConnectionStrings["Expert ExchangeConnectionString"].ConnectionString;
        
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO TestData (Column1, Column2, Column3, Column4, Column5, Column6) VALUES (@c1, @c2, @c3, @c4, @c5, @c6)", conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@c1", col1);
                cmd.Parameters.AddWithValue("@c2", col2);
                cmd.Parameters.AddWithValue("@c3", col3);
                cmd.Parameters.AddWithValue("@c4", col4);
                cmd.Parameters.AddWithValue("@c5", col5);
                cmd.Parameters.AddWithValue("@c6", col6);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
 
    private void UpdateRow(int dataID, string col1, string col2, string col3, string col4, string col5, string col6)
    {
        string connStr = ConfigurationManager.ConnectionStrings["Expert ExchangeConnectionString"].ConnectionString;
 
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE TestData SET Column1=@c1, Column2=@c2, Column3=@c3, Column4=@c4, Column5=@c5, Column6=@c6 WHERE DataID=@dataId", conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@c1", col1);
                cmd.Parameters.AddWithValue("@c2", col2);
                cmd.Parameters.AddWithValue("@c3", col3);
                cmd.Parameters.AddWithValue("@c4", col4);
                cmd.Parameters.AddWithValue("@c5", col5);
                cmd.Parameters.AddWithValue("@c6", col6);
                cmd.Parameters.AddWithValue("@dataId", dataID);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.GridView1.DataSource = GetDataTable();
            this.GridView1.DataBind();
        }
    }
 
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // is 2nd column clicked
        if (e.CommandName == "MyCommand")
        {
            this.Panel1.Visible = true;
            this.InsertButton.Visible = false;
            this.UpdateButton.Visible = true;
            int index = int.Parse((string)e.CommandArgument);
            int primaryKey = (int)this.GridView1.DataKeys[index].Value;
            DataRow row = this.GetRow(primaryKey);
            TextBox1.Text = row[0].ToString();
            TextBox2.Text = row[1].ToString();
            TextBox3.Text = row[2].ToString();
            TextBox4.Text = row[3].ToString();
            TextBox5.Text = row[4].ToString();
            TextBox6.Text = row[5].ToString();
            TextBox7.Text = row[6].ToString();
        }
    }
 
    protected void AddButton_Click(object sender, EventArgs e)
    {
        this.Panel1.Visible = true;
        this.InsertButton.Visible = true;
        this.UpdateButton.Visible = false;
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
        TextBox4.Text = "";
        TextBox5.Text = "";
        TextBox6.Text = "";
        TextBox7.Text = "";
    }
    
    protected void CancelButton_Click(object sender, EventArgs e)
    {
        this.Panel1.Visible = false;
    }
 
    protected void InsertButton_Click(object sender, EventArgs e)
    {
        this.AddRow(this.TextBox2.Text, this.TextBox3.Text, this.TextBox4.Text, this.TextBox5.Text, this.TextBox6.Text, this.TextBox7.Text);
        this.Panel1.Visible = false;
        this.GridView1.DataSource = GetDataTable();
        this.GridView1.DataBind();
    }
 
    protected void UpdateButton_Click(object sender, EventArgs e)
    {
        this.UpdateRow(int.Parse(this.TextBox1.Text), this.TextBox2.Text, this.TextBox3.Text, this.TextBox4.Text, this.TextBox5.Text, this.TextBox6.Text, this.TextBox7.Text);
        this.Panel1.Visible = false;
        this.GridView1.DataSource = GetDataTable();
        this.GridView1.DataBind();
    }
}

Open in new window

Capture.JPG
0
 

Author Comment

by:amukta
ID: 24359739
Hi! wht1986,

Thank you sooo...much!
0
 

Author Comment

by:amukta
ID: 24360764
Hi! wht1986,

I have a question reg. the code you've pasted above.
How do I validate the textbox values on insert and update using javascript..for eg:if they are blank, numeric, etc.

Could you please let me know ASAP.

It's very urgent.

Any Code/logic is greatly appreciated.

Thanks a million in advance!
0
 
LVL 12

Expert Comment

by:wht1986
ID: 24360913
Just use the built in asp.net validators, there is one for required fields and others you can use for type validation and ranges etc.
0
 

Author Comment

by:amukta
ID: 24380758
Hi!  wht1986,
 
In the above code you've posted,
how do I check if the duplicates records are being inserted , when adding a row in c#? Could you please
help me with that.

Any logic/code is greatly appreciated. I'm using a stored procedure to insert  and update records into the table, but i cannot use output parameter  AS MY DATABASE LAYER HAS THE CODE WRITTEN THAT WAY and hence cannot PASS THE Error message from sql server to c#.

It's really urgent.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
While opting for any web-to-print solution, you need to discuss with your team and some of your end users and know their opinions about your decisions. In this article we list down some questions you need to ask yourself.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

688 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