Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. Please help me out. I am a beginner and I need help

I have id, subject, date, attachment in database.

What I've done is I have taken a form used connection, adapter command and inserted the record in the database and displayed the record in a grid.

Now my requirement is if we take 2 command buttons, edit and delete in the grid and first if we click on edit button; How can I get the details of that selected column and goto another page where there is ID readonly, subject----textarea, date, attachment-fileupload - and in this screen already that particular selected records data should be FILLED IN the controls and if needed then I can edit the data in the controls and then I place an update button and when the update button is clicked, it should be updated. The same case for delete. When I click on delete that particular record should be deleted. Can you show this scenario with 2 simple columns. If you have time. I am struggling but not getting it right and I don't have any ideas how to proceed further.

XML
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Admin/ADMINmaster.master" CodeFile="AddMeeting.aspx.cs" Inherits="Admin_AddMeeting" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>







<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .style5
    {
        width: 101%;
    }
        .style12
        {
            width: 91px;
            text-align: center;
        }
        .style17
    {
        width: 10px;
            text-align: center;
        }
    .style20
    {
        width: 147px;
    }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <table class="style5">
    <tr>
                <td class="style20" colspan="2" align="center" >
                    <table align="center" width="898px" cellpadding="4" cellspacing="4" >
                        <tr>
                        <td colspan="5" style="text-align: center; font-weight: bold;" >
                            Add Meeting
                        </td>
                        </tr>
                        <%--<tr>
                            <td>
                                ID
                            </td>
                            <td align="left">
                                <asp:TextBox ID="txtId" runat="server" ReadOnly="true"></asp:TextBox>
                            </td>
                        </tr>--%>
                        <tr>
                            <td>
                                Subject
                            </td>
                            <td align="left">
                       <asp:TextBox ID="TextboxSubject"  Height="100px" Width="400px" TextMode="MultiLine" runat ="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="rfvSubject" runat="server"
                                    ControlToValidate="TextboxSubject" Display="Dynamic"
                                    ErrorMessage="Please Enter the Subject.">Please Enter the Subject.</asp:RequiredFieldValidator>
                                                     </td>
                        </tr>
                        <tr>
                            <td>
   Date
                            </td><td align="left" ><asp:TextBox ID="TextBox1" runat="server" CausesValidation="True"></asp:TextBox>
                                <cc1:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="TextBox1">
                                </cc1:CalendarExtender>
                                                         <asp:RequiredFieldValidator ID="rfvDate" runat="server"
                                                             ControlToValidate="TextBox1" Display="Dynamic"
                                                             ErrorMessage="Please Enter the Date.">Please Enter
                                the Date.</asp:RequiredFieldValidator>
     </td>
                        </tr>
<tr>
                            <td>
                            Attachment


                            </td><td align="left"> <asp:FileUpload ID="fileulpoad" runat="server" />

                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                    ControlToValidate="fileulpoad" Display="Dynamic"
                                    ErrorMessage="Please Attach a File.">Please Attach a File.</asp:RequiredFieldValidator>

                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;</td><td align="left">
                                <asp:Button ID="btnAdd" runat="server"
                                    Text="Add Meeting" OnClick = "Add"
        style="height: 26px" /></td>
                        </tr>
                        <tr>
                        <td colspan="5">
                            <asp:GridView ID="GridView1" runat="server"
        Width="898px" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid"
        BorderWidth="3px" CellPadding="4" AutoGenerateColumns="False"

        style="margin-left: 0px" CaptionAlign="Top" CellSpacing="2"
        ForeColor="Blue" RowHeaderColumn="NameOfWork" AllowSorting="True"
                            onsorting="GridView1_Sorting1"
                                    onselectedindexchanged="GridView1_SelectedIndexChanged"
                                DataKeyNames="MT_ID" >

        <FooterStyle BackColor="#CCCCCC" />
        <RowStyle BackColor="White" />

        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
        <EditRowStyle Height="120px" />
         <Columns>

          <asp:BoundField DataField ="MT_ID"  HeaderText="ID" ReadOnly="True"   >
                <ControlStyle BorderWidth="1000px" Font-Bold="true" />

                <ItemStyle Width="90px"  ForeColor="#CC0099" />
            </asp:BoundField>

         <asp:TemplateField    HeaderText="Subject"    ItemStyle-Width="281px"   ItemStyle-ForeColor="#CC0099">
         <ItemTemplate >

          <asp:HyperLink ID="Open" Font-Bold="true"   NavigateURL='<%# imageURL(DataBinder.Eval(Container.DataItem, "Attachment")) %>' Text='<%# Eval("Subject") %>' Target="_blank"  runat="server" />

         <%--asp:LinkButton ID ="linksubject"    runat ="server" Text ='<%#Eval("Subject") %>' CommandArgument ="MT_ID" CommandName ="Subject"></asp:LinkButton>       --%>
         </ItemTemplate>


             <ItemStyle ForeColor="#CC0099" Width="281px" />


         </asp:TemplateField>
         <asp:BoundField DataField ="ATTACHMENT"  HeaderText="Attachment" >
                <ControlStyle BorderWidth="1000px" Font-Bold="true" />

                <ItemStyle Width="181px" ForeColor="#CC0099" />
            </asp:BoundField>
          <asp:BoundField DataField ="MTDATE"  HeaderText="Date" SortExpression="MTDATE"
                 DataFormatString="{0:dd/MM/yyyy}" >
                <ControlStyle BorderWidth="1000px" Font-Bold="true" />

                <ItemStyle Width="181px" ForeColor="#CC0099" />
            </asp:BoundField>
             <asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" />
             <asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete" />
         </Columns>
         </asp:GridView>
                        </td>
                        </tr>
                        <tr align="right" valign="middle"><td align="center">&nbsp;</td><td></td></tr>

                                               </table>
                </td>
            </tr>
        <tr>
            <td style="text-align: center">
                <asp:MultiView ID="mv_AddMeeting" runat="server" ActiveViewIndex="0">
                    <asp:View ID="viewAddMeeting" runat="server">
                    <table class="style5">
                    <tr align="center" >
                    <td>
                        &nbsp;</td></tr>







                            </table>
                    </asp:View>
                    </asp:MultiView>
            </td>
        </tr>
    </table>
</asp:Content>

-----.aspx.cs-------

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
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;
public partial class Admin_AddMeeting : System.Web.UI.Page
{
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";
    DataSet ds = new DataSet();
    SqlDataAdapter da; 
    
    String strConnString = ConfigurationManager.ConnectionStrings["hmwssbConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {   
        BLCGM obj = new BLCGM();
        obj.User = Session["UserName"].ToString();
        string select = ("select MT_ID,Subject,attachment,MTDate from minutes_meeting");
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        SqlCommand cmd = new SqlCommand(select, con);
        cmd.ExecuteNonQuery();
        BindData();
        if (obj.User == "Admin")
        {
            BindData();

        }
        //else
        //{
        //    //Response.Redirect("~/Admin/ADMIN.aspx");
        //}
 
    }
    private void BindData()
    {
        DataSet ds = DataHelper.ExecuteDataSet("Select  * from MINUTES_MEETING");
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    public string imageURL(object SmallImage)
    {
        return ("~/Attachment/" + SmallImage);
    }
    protected void Add(object sender, EventArgs e)
    {
        string subject = TextboxSubject.Text;
        string date = TextBox1.Text;
        //string filename = Path.GetFileName(fileulpoad.PostedFile.FileName);
        string filename = Server.MapPath("~/Attachment/" + fileulpoad.FileName);
        string file = fileulpoad.FileName;
        //fileulpoad.SaveAs("~/Attachment/attachment/" + filename);
        fileulpoad.SaveAs(filename);
        string insert = "insert into minutes_meeting(Subject,attachment,MTDate)  values('" + subject + "','" + file + "','" + date + "')";
        SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        SqlCommand cmd = new SqlCommand(insert, con);
        cmd.ExecuteNonQuery();
        BindData();
        TextboxSubject.Text = "";
        TextBox1.Text = "";
    }
    protected void lnkAdmin_Click(object sender, EventArgs e)
    {
    }
    

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        //DataTable dataTable = gridView1.DataSource as DataTable;
       
       
    }
    private void SortGridView(string sortExpression, string direction)
    {

        DataTable dt = new DataTable();
        DataSet ds = DataHelper.ExecuteDataSet("Select  * from MINUTES_MEETING");
        dt = ds.Tables[0];
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }
 
 
protected void  GridView1_Sorting1(object sender, GridViewSortEventArgs e)
{
    string sortExpression = e.SortExpression;
    ViewState["SortExpression"] = sortExpression;

    if (GridViewSortDirection == SortDirection.Ascending)
    {
        GridViewSortDirection = SortDirection.Descending;
        SortGridView(sortExpression, DESCENDING);
    }
    else
    {
        GridViewSortDirection = SortDirection.Ascending;
        SortGridView(sortExpression, ASCENDING);
    } 

}

private SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;
        return (SortDirection)ViewState["sortDirection"];
    }
    set { ViewState["sortDirection"] = value; }
}


protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    
}
}
Posted
Updated 27-May-10 3:00am
v5
Comments
Johnny J. 27-May-10 8:42am    
OK, good luck to somebody editing this question... :)
Tom Deketelaere 27-May-10 8:46am    
Wasn't that difficult, uncheck a checkbox, add a code block and done :)
Johnny J. 27-May-10 8:50am    
But you didn't edit all the spelling errors :)
Johnny J. 27-May-10 8:58am    
I've removed the worst spelling errors, but not gone over the sentence structure and grammar too much... Haven't got that much time :)

1 solution

There are a few ways to do this:

The first way I am going to show you is an easy workaround, although not the most professional fix.

In the aspx file, place:
<asp:commandfield headertext="Edit/View" showselectbutton="True" xmlns:asp="#unknown">
inside of your gridview.

Then add
onselectedindexchanged="GridView1_SelectedIndexChanged"
into your asp gridview declaration.

Like so
<asp:gridview id="GridView1" runat="server" datasourceid="SqlDataSource1" cssclass="GridView" xmlns:asp="#unknown">
                                AllowPaging="True" AllowSorting="True"
                                AutoGenerateColumns="False" 
                                BorderStyle="Ridge" BorderWidth="2px" 
                                OnRowCommand="GridView1_RowCommand" 
                                onselectedindexchanged="GridView1_SelectedIndexChanged" ></asp:gridview>



In the code behind part create this function for the GridView1_SelectedIndexChanged.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
        int index = GridView1.SelectedIndex;
        Session["selectedId"] = GridView1.Rows[index].Cells[1].Text;
        TabContainer1.ActiveTabIndex = 2;
}


I was using this inside of a TabContainer. If you want to change it to another aspx page replace TabContainer1.ActiveTabIndex = 2; with Response.Redirect("~/yourOtherPage.aspx"); or you can also use ServerTransfer, I believe, although I am not familiar with that method.

You can create Session variables to store the data in. Then during the page load of your other page, check these session state variables to see if they have values. If they do you can insert them into textfields to edit.

Also, GridView1.Rows[index].Cells[1].Text; is used to access the values in the gridview at specific locations. Cells[#] is which column of the gridview you want to access.

The Second Option is to follow the example in Ashrafur Rahaman's article Editable GridView in ASP.NET 2.0, which is a more professional solution then the above.

His example is a good starting place, although it might take you a little bit more time to study and get through the entire article it is worth knowing and easy to add to once you understand how a gridview works. His example will show you how to create these commands once inside of them you will access the information, save it, and change pages like above.

For a more thorough look at how to access items in a gridview check out azamsharp's article at Accessing the different controls inside a GridView control.

I hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900