Yasserzaid’s Weblog

December 21, 2008

AJAX Collapsible Panel with Gridview (Master and Detail)

Filed under: AJAX, ASP.Net — Tags: , — yasserzaid @ 10:14 pm

Hi

try this example:

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "<a href="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title>Untitled Page</title>
    <link type="text/css" rel="Stylesheet" href="Assets/css/dialog.css" />
    <link type="text/css" rel="Stylesheet" href="Assets/css/pager.css" />
    <link type="text/css" rel="Stylesheet" href="Assets/css/grid.css" />
</head>
<body>
    <form id="form1" runat="server">
        <ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server" />
        <asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
            SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], COUNT([OrderID]) TotalOrders FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID] Group By [Customers].[CustomerID], [Customers].[CompanyName]">
        </asp:SqlDataSource>
        <div id="dlg" class="dialog" style="width: 700px">
            <div class="header" style="cursor: default">
                <div class="outer">
                    <div class="inner">
                        <div class="content">
                            <h2>
                                Northwind: Orders By Customer</h2>
                        </div>
                    </div>
                </div>
            </div>
            <div class="body">
                <div class="outer">
                    <div class="inner">
                        <div class="content">
                            <asp: Panel CssClass="grid" ID="pnlCust" runat="server">
                                <asp:UpdatePanel ID="pnlUpdate" runat="server">
                                    <ContentTemplate>
                                        <asp: GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
                                            DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
                                            <Columns>
                                                <asp:TemplateField>
                                                    <ItemTemplate>
                                                        <asp: Panel CssClass="group" ID="pnlCustomer" runat="server">
                                                            <asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
                                                                Style="margin-right: 5px;" runat="server" /><span class="header">
                                                                    <%#Eval("CustomerID")%>
                                                                    :
                                                                    <%#Eval("CompanyName")%>
                                                                    (<%#Eval("TotalOrders")%>
                                                                    Orders) </span>
                                                        </asp: Panel>
                                                        <asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
                                                            SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = @CustomerID)">
                                                            <SelectParameters>
                                                                <asp: Parameter Name="CustomerID" Type="String" DefaultValue="" />
                                                            </SelectParameters>
                                                        </asp:SqlDataSource>
                                                        <asp: Panel Style="margin-left: 20px; margin-right: 20px" ID="pnlOrders" runat="server">
                                                            <asp:GridView AutoGenerateColumns="False" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
                                                                runat="server" EnableViewState="False">
                                                                <RowStyle CssClass="row" />
                                                                <AlternatingRowStyle CssClass="altrow" />
                                                                <Columns>
                                                                    <asp:TemplateField>
                                                                        <ItemTemplate>
                                                                            <%# Container.DataItemIndex + 1 %>
                                                                        </ItemTemplate>
                                                                        <ItemStyle CssClass="rownum" />
                                                                    </asp:TemplateField>
                                                                    <asp:BoundField HeaderText="Order ID" DataField="OrderID" >
                                                                        <ItemStyle Width="80px" />
                                                                    </asp:BoundField>
                                                                    <asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:dd/MM/yyyy}" >
                                                                        <ItemStyle Width="100px" />
                                                                    </asp:BoundField>
                                                                    <asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:dd/MM/yyyy}" >
                                                                        <ItemStyle Width="110px" />
                                                                    </asp:BoundField>
                                                                    <asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}" >
                                                                        <ItemStyle HorizontalAlign="Right" Width="50px" />
                                                                    </asp:BoundField>
                                                                    <asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:dd/MM/yyyy}" >
                                                                        <ItemStyle Width="100px" />
                                                                    </asp:BoundField>
                                                                </Columns>
                                                            </asp:GridView>
                                                        </asp: Panel>
                                                        <ajaxToolkit:CollapsiblePanelExtender ID="cpe" runat="Server" TargetControlID="pnlOrders"
                                                            CollapsedSize="0" Collapsed="True" ExpandControlID="pnlCustomer" CollapseControlID="pnlCustomer"
                                                            AutoCollapse="False" AutoExpand="False" ScrollContents="false" ImageControlID="imgCollapsible"
                                                            ExpandedImage="~/Assets/img/minus.png" CollapsedImage="~/Assets/img/plus.png"
                                                            ExpandDirection="Vertical" />
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                        </asp:GridView>
                                    </ContentTemplate>
                                </asp:UpdatePanel>
                            </asp: Panel>
                        </div>
                    </div>
                </div>
            </div>
            <div class="footer">
                <div class="outer">
                    <div class="inner">
                        <div class="content">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlDataSource ctrl = e.Row.FindControl("sqlDsOrders") as SqlDataSource;
            if (ctrl != null && e.Row.DataItem != null)
            {
                ctrl.SelectParameters["CustomerID"].DefaultValue = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
            }
        }
    }
}

in web.config

<connectionStrings>
  <add name="Northwind" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Hope it helps

Good Luck

AJAX Accordion Extender with Data from Database

Filed under: AJAX — Tags: , — yasserzaid @ 10:10 pm

Hi

try this example using Northwind Database

.aspx

<head runat="server">
    <title>AJAX DataBound Accordion</title>
   
    <style type="text/css">
   
    body {
    font-family: verdana;
    font-size: 11px;
    }
   
    .header,.selected {
    width: 300px;
    background-color: #c0c0c0;
    margin-bottom:2px;
    padding:2px;
    color:#444444;
    font-weight:bold;
    cursor:pointer;
    }
   
    .content {
    width:300px;
    margin-bottom:2px;
    padding:2px;
    }
   
    .selected,.content {
    border:solid 1px #666666;
    }
   
   
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
        </div>
        <ajaxToolkit:Accordion ID="Accordion1" runat="server" TransitionDuration="100" FramesPerSecond="200" FadeTransitions="true" RequireOpenedPane="false" OnItemDataBound="Accordion1_ItemDataBound"
            ContentCssClass="content" HeaderCssClass="header" HeaderSelectedCssClass="selected">
            <HeaderTemplate>
                <%#DataBinder.Eval(Container.DataItem,"categoryName") %>
            </HeaderTemplate>
            <ContentTemplate>
                <asp:HiddenField ID="txt_categoryID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"categoryID") %>' />
                <asp:GridView ID="GridView1" runat="server" RowStyle-BackColor="#ededed" RowStyle-HorizontalAlign="Left"
                    AutoGenerateColumns="false" GridLines="None" CellPadding="2" CellSpacing="2"
                    Width="300px">
                    <Columns>
                        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Product Name" HeaderStyle-BackColor="#d1d1d1"
                            HeaderStyle-ForeColor="#777777">
                            <ItemTemplate>
                                <%#DataBinder.Eval(Container.DataItem,"productName") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </ContentTemplate>
        </ajaxToolkit:Accordion>
  </div>
       
    </form>
</body>
</html>

in code behind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class ajax_data_ajax_data_accordion : System.Web.UI.Page
{
    string conString = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getCategories();
        }
    }

    public void getCategories()
    {
        SqlConnection sqlConn = new SqlConnection(conString);
        sqlConn.Open();
        SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Categories", sqlConn);
        sqlSelect.CommandType = System.Data.CommandType.Text;
        SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
        DataSet myDataset = new DataSet();
        sqlAdapter.Fill(myDataset);
        sqlConn.Close();

        Accordion1.DataSource = myDataset.Tables[0].DefaultView;
        Accordion1.DataBind();

    }
    protected void Accordion1_ItemDataBound(object sender, AjaxControlToolkit.AccordionItemEventArgs e)
    {
        if (e.ItemType == AjaxControlToolkit.AccordionItemType.Content)
        {
            SqlConnection sqlConn = new SqlConnection(conString);
            sqlConn.Open();
            SqlCommand sqlSelect = new SqlCommand("SELECT productName FROM Products where categoryID = '" + ((HiddenField)e.AccordionItem.FindControl("txt_categoryID")).Value + "'", sqlConn);
            sqlSelect.CommandType = System.Data.CommandType.Text;
            SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
            DataSet myDataset = new DataSet();
            sqlAdapter.Fill(myDataset);
            sqlConn.Close();

            GridView grd = new GridView();

            grd = (GridView)e.AccordionItem.FindControl("GridView1");
            grd.DataSource = myDataset;
            grd.DataBind();
        }
    }
}

in web.config

<connectionStrings>
  <add name="SqlConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"/>
 </connectionStrings>

Good Luck

Change User Email with Membership

Filed under: ASP.Net — Tags: , — yasserzaid @ 10:06 pm

Try this example:

http://forums.asp.net/t/1281001.aspx
http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.email.aspx
Dim user As MembershipUser
user = Membership.GetUser(UserName)

user.Email = TxtBxNewEmail.Text

Membership.UpdateUser(user)

but check for email availability

public bool CheckEmail()
    {
        bool emailExsit = false;
        MembershipUserCollection users = Membership.FindUsersByEmail(Email.Text);
        foreach (MembershipUser user in users)
        {
            if (Email.Text == user.Email)
            {
                emailExsit = true;
                break;
            }
            else
            {
                emailExsit = false;
            }
        }
        return emailExsit;

    }

Good Luck

Count Characters Remaining in TextBox

Filed under: ASP.Net, Javascript — yasserzaid @ 9:47 pm

Try this example:

<script runat=”server”>
protected void Page_Load(object sender, EventArgs e)
{

    txtCount.Text = txtInput.MaxLength.ToString();
   
    txtInput.Attributes.Add(“onKeyUp”,
       “javascript:document.getElementById(‘”+ txtCount.ClientID +
       “‘).setAttribute(‘value’, (” + txtInput.MaxLength +
       ” – parseInt(document.getElementById(‘” + txtInput.ClientID +
       “‘).getAttribute(‘value’).length)));”);
}
public int MaxLength
{
    get { return txtInput.MaxLength; }
    set { txtInput.MaxLength = value; }
}
</script>

<table>
 <tr>
  <td>
   <asp:Label ID=”Label1″ runat=”server”>Characters Left: </asp:Label>
   <asp:TextBox ID=”txtCount” runat=”server”
            BorderStyle=”None” ReadOnly=”True”>0</asp:TextBox>
  </td>
 </tr>
 <tr>
  <td>
   <asp:TextBox ID=txtInput runat=”server” BorderColor=”Gray”
           BorderStyle=”Solid” BorderWidth=”1px”
           Height=”125px” MaxLength=”2000″
           TextMode=”MultiLine”
           Width=”350px”></asp:TextBox>
  </td>
 </tr>
</table>

Good Luck

Date Compare not Equal or Greater today

Filed under: ASP.Net — Tags: , — yasserzaid @ 9:44 pm

Hi

try this example:

Date in MM/dd/yyyy format
    <asp:TextBox ID=”text_Date” runat=”server”></asp:TextBox>&nbsp;
    <asp:CompareValidator ID=”CompareValidator1″ runat=”server” ControlToValidate=”text_Date”
        ErrorMessage=”The date must be greater than or equal to today.” Operator=”GreaterThanEqual”></asp:CompareValidator>
protected void Page_Load(object sender, EventArgs e)
    {
        CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString();
    }

Good Luck

Find Control in DataList and GridView

Filed under: ASP.Net — yasserzaid @ 9:42 pm

Try this example:

//— DataList

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lbl_Desc = (Label)e.Item.FindControl(“lbl_Desc”);
            lbl_Desc.Text = lbl_Desc.Text.Substring(0, 180).ToString() + “…”;
        }
    }

 

//— Gridview

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //– find control in row
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   DropDownList cmbType = (DropDownList)e.Row.FindControl(“cmbType”);

 
 }

//– find control in footer
if (e.Row.RowType == DataControlRowType.Footer)
{
    DropDownList cmbNewType = (DropDownList)e.Row.FindControl(“cmbNewType”);
   
}

}

//– Find Control in Edit mode of Gridview

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Edit)
            {
                TextBox box = e.Row.FindControl(“TextBox1″) as TextBox;
            }
        }
    }

Good Luck

Insert checked item in CheckListBox

Filed under: ASP.Net — yasserzaid @ 9:38 pm

Hi

try this example to loop on Checked item(s) in CheckListBox and Insert them in Database    public int Add_Project_Applications()
    {
        for (int i = 0; i < cbx_Application.Items.Count ; i++)
        {
            if (cbx_Application.Items[i].Selected)
            {
               obj_Project_Applications.Application_Id =int.Parse(cbx_Application.Items[i].Value);
               obj_Project_Applications.Project_Id =int.Parse( lbl_Project_Id.Text);
               rows=obj_Project_Applications.Insert_Project_Application();
            }
           
        }
        return rows;
    }

Good Luck

Insert and Update and Delete Without SqlDataSource

Filed under: ASP.Net — yasserzaid @ 9:35 pm

try this example without using SqlDataSource

.aspx

<%@ 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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:label id="lblMessage" runat="server" enableviewstate="False" Font-Bold="True" />
	<asp:gridview id="gvShippers" runat="server" allowpaging="True" allowsorting="True"
		autogeneratecolumns="False" datakeynames="ShipperID" emptydatatext="There are no data records to display."
		onpageindexchanging="gvShippers_PageIndexChanging" onrowcancelingedit="gvShippers_RowCancelingEdit"
		onrowcommand="gvShippers_RowCommand" onrowdeleting="gvShippers_RowDeleting" onrowediting="gvShippers_RowEditing"
		onrowupdating="gvShippers_RowUpdating" onsorting="gvShippers_Sorting" showfooter="True"
		style="margin-top: 20px;" CellPadding="4" ForeColor="#333333" GridLines="None">
		<columns>
			<asp:templatefield>
				<itemtemplate>
					<asp:linkbutton id="btnSelect" runat="server" commandname="Select" text="Select" />
					<asp:linkbutton id="btnEdit" runat="server" commandname="Edit" text="Edit" />
					<asp:linkbutton id="btnDelete" runat="server" commandname="Delete" text="Delete" />
				</itemtemplate>
				<edititemtemplate>
					<asp:linkbutton id="btnUpdate" runat="server" commandname="Update" text="Update" />
					<asp:linkbutton id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
				</edititemtemplate>
				<footertemplate>
					<asp:linkbutton id="btnInsert" runat="server" commandname="Insert" text="Insert" />
				</footertemplate>
			</asp:templatefield>
			<asp:boundfield datafield="ShipperID" headertext="ShipperID" insertvisible="False"
				sortexpression="ShipperID" />
			<asp:templatefield headertext="CompanyName" sortexpression="CompanyName">
				<itemtemplate>
					<%# Eval("CompanyName") %>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtCompanyName" runat="server" text='<%# Eval("CompanyName") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtCompanyName" runat="server" />
				</footertemplate>
			</asp:templatefield>
			<asp:templatefield headertext="Phone" sortexpression="Phone">
				<itemtemplate>
					<%# Eval("Phone") %>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtPhone" runat="server" text='<%# Eval("Phone") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtPhone" runat="server" />
				</footertemplate>
			</asp:templatefield>
		</columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#EFF3FB" />
        <EditRowStyle BackColor="#2461BF" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
	</asp:gridview>

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

 .aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    private string Sort
    {
        get
        {
            return String.Concat(
                    this.SortExpression,
                    (this.SortDirection == SortDirection.Ascending) ? " ASC" : " DESC");
        }
    }

    private SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Ascending;
            }

            return (SortDirection)ViewState["SortDirection"];
        }
        set { ViewState["SortDirection"] = value; }
    }

    private string SortExpression
    {
        get
        {
            if (ViewState["SortExpression"] == null)
            {
                ViewState["SortExpression"] = "ShipperID";
            }

            return ViewState["SortExpression"].ToString();
        }
        set { ViewState["SortExpression"] = value; }
    }

    private void SetData()
    {
        SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("SELECT * FROM [Shippers]", conn);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);

        try
        {
            conn.Open();
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            DataView dv = dt.DefaultView;
            dv.Sort = this.Sort;

            gvShippers.DataSource = dv;
            gvShippers.DataBind();
        }
        finally
        {
            conn.Close();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.SetData();
        }
    }

    protected void gvShippers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShippers.PageIndex = e.NewPageIndex;

        this.SetData();
    }

    protected void gvShippers_Sorting(object sender, GridViewSortEventArgs e)
	{
        if (this.SortExpression.Equals(e.SortBLOCKED EXPRESSION)
        {
            this.SortDirection = (this.SortDirection == SortDirection.Ascending) ? SortDirection.Descending :SortDirection.Ascending;
        }
        else
        {
            this.SortDirection = SortDirection.Ascending;
        }

        this.SortExpression = e.SortExpression;

        this.SetData();
	}

    protected void gvShippers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvShippers.EditIndex = e.NewEditIndex;

        this.SetData();
    }

    protected void gvShippers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvShippers.EditIndex = -1;

        this.SetData();
    }

    protected void gvShippers_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gvr = gvShippers.Rows[e.RowIndex];

        TextBox txtCompanyName = gvr.FindControl("txtCompanyName") as TextBox;
        TextBox txtPhone = gvr.FindControl("txtPhone") as TextBox;

        if (txtCompanyName == null) { return; }
        if (txtPhone == null) { return; }

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(
            "UPDATE [Shippers] SET [CompanyName] = @CompanyName, [Phone] = @Phone WHERE (ShipperID = @ShipperID)",
            conn);
        cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[gvr.RowIndex]["ShipperID"]);
        cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
        cmd.Parameters.AddWithValue("Phone", txtPhone.Text);

        try
        {
            conn.Open();

            if (cmd.ExecuteNonQuery().Equals(1))
            {
                lblMessage.Text = String.Format(
                    "Shipper '{0}' successfully updated.",
                    cmd.Parameters["ShipperID"].Value);

                gvShippers.EditIndex = -1;

                this.SetData();
            }
        }
        finally
        {
            conn.Close();
        }
    }

    protected void gvShippers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(
            "DELETE FROM [Shippers] WHERE (ShipperID = @ShipperID)",
            conn);
        cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[e.RowIndex]["ShipperID"]);

        try
        {
            conn.Open();

            if (cmd.ExecuteNonQuery().Equals(1))
            {
                lblMessage.Text = String.Format(
                    "Shipper '{0}' successfully deleted.",
                    cmd.Parameters["ShipperID"].Value);

                this.SetData();
            }
        }
        finally
        {
            conn.Close();
        }
    }

    protected void gvShippers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            LinkButton btnInsert = e.CommandSource as LinkButton;

            if (btnInsert == null) { return; }

            GridViewRow gvr = btnInsert.NamingContainer as GridViewRow;

            if (gvr == null) { return; }

            TextBox txtCompanyName = gvr.FindControl("txtCompanyName") as TextBox;
            TextBox txtPhone = gvr.FindControl("txtPhone") as TextBox;

            if (txtCompanyName == null) { return; }
            if (txtPhone == null) { return; }

            SqlConnection conn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand(
                "INSERT INTO [Shippers] ([CompanyName], [Phone]) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY()",
                conn);
            cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
            cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
            cmd.Parameters.Add("ShipperID", SqlDbType.Int);
            cmd.Parameters["ShipperID"].Direction = ParameterDirection.Output;

            try
            {
                conn.Open();

                if (cmd.ExecuteNonQuery().Equals(1))
                {
                    lblMessage.Text = String.Format(
                        "Shipper '{0}' successfully added.",
                        cmd.Parameters["ShipperID"].Value);

                    this.SetData();
                }
            }
            finally
            {
                conn.Close();
            }
        }
    }

}
Good Luck

Insert and Update and delete using SqlDataSource

Filed under: ASP.Net — yasserzaid @ 9:33 pm

try this example to insert / update and delete using SqlDataSource

.aspx

<%@ 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>Grid View Add Update Delete</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:label id="lblMessage" runat="server" Font-Bold="True" />
	<asp:gridview id="gvShippers" runat="server" allowpaging="True" allowsorting="True"
		autogeneratecolumns="False" datakeynames="ShipperID" datasourceid="sdsShippers"
		emptydatatext="There are no data records to display." showfooter="True"
		style="margin-top: 20px;" onrowcommand="gvShippers_RowCommand"
		onrowdeleted="gvShippers_RowDeleted" onrowupdated="gvShippers_RowUpdated"
		onpageindexchanged="gvShippers_PageIndexChanged"
		onrowediting="gvShippers_RowEditing"
		onselectedindexchanged="gvShippers_SelectedIndexChanged" CellPadding="4" ForeColor="#333333">
		<columns>
			<asp:templatefield headertext="Actions">
				<itemtemplate>
					<asp:linkbutton id="btnEdit" runat="server" commandname="Edit" text="Edit" CausesValidation="False" />
					<asp:linkbutton id="btnDelete" runat="server" commandname="Delete" onclientclick="return confirm('Are you sure you want to delete this shipper?');"
						text="Delete" CausesValidation="False" />
					<asp:linkbutton id="btnSelect" runat="server" commandname="Select" text="Select" CausesValidation="False" />
				</itemtemplate>
				<edititemtemplate>
					<asp:linkbutton id="btnUpdate" runat="server" commandname="Update" text="Update" CausesValidation="False" />
					<asp:linkbutton id="btnCancel" runat="server" commandname="Cancel" text="Cancel" CausesValidation="False" />
				</edititemtemplate>
				<footertemplate>
					<asp:linkbutton id="btnInsert" runat="server" commandname="Insert" text="Insert" />
					<asp:linkbutton id="btnCancel" runat="server" commandname="Cancel" text="Cancel" CausesValidation="False" />
				</footertemplate>
			</asp:templatefield>
			<asp:boundfield datafield="ShipperID" headertext="ShipperID" readonly="True"
				sortexpression="ShipperID" />
			<asp:templatefield headertext="CompanyName" sortexpression="CompanyName">
				<itemtemplate>
					<%# Eval("CompanyName") %>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtCompanyName" runat="server" text='<%# Bind("CompanyName") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtCompanyName" runat="server" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtCompanyName"
                        ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
				</footertemplate>
			</asp:templatefield>
			<asp:templatefield headertext="Phone" sortexpression="Phone">
				<itemtemplate>
					<%# Eval("Phone")%>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtPhone" runat="server" text='<%# Bind("Phone") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtPhone" runat="server" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPhone"
                        ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
				</footertemplate>
			</asp:templatefield>
		</columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#EFF3FB" />
        <EditRowStyle BackColor="#2461BF" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
	</asp:gridview>
	<asp:sqldatasource id="sdsShippers" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
		deletecommand="DELETE FROM [Shippers] WHERE [ShipperID] = @ShipperID" insertcommand="INSERT INTO [Shippers] ([CompanyName], [Phone]) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY();"
		selectcommand="SELECT * FROM [Shippers]" updatecommand="UPDATE [Shippers] SET [CompanyName] = @CompanyName, [Phone] = @Phone WHERE [ShipperID] = @ShipperID"
		oninserted="sdsShippers_Inserted">
		<updateparameters>
			<asp:parameter name="ShipperID" type="Int32" />
			<asp:parameter name="CompanyName" type="String" />
			<asp:parameter name="Phone" type="String" />
		</updateparameters>
		<insertparameters>
			<asp:parameter direction="Output" name="ShipperID" type="Int32" />
			<asp:parameter name="CompanyName" type="String" />
			<asp:parameter name="Phone" type="String" />
		</insertparameters>
		<deleteparameters>
			<asp:parameter name="ShipperID" type="Int32" />
		</deleteparameters>
	</asp:sqldatasource>
        <br />

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

 .aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void gvShippers_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvShippers.EditIndex = -1;

        lblMessage.Text = String.Format(
            "Shipper '{0}' successfully selected.",
            gvShippers.SelectedDataKey["ShipperID"]);
    }

    protected void gvShippers_PageIndexChanged(object sender, EventArgs e)
    {
        gvShippers.EditIndex = -1;
        gvShippers.SelectedIndex = -1;
    }

    protected void gvShippers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvShippers.SelectedIndex = -1;
    }

    protected void gvShippers_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        if ((e.Exception == null) && e.AffectedRows.Equals(1))
        {
            lblMessage.Text = String.Format(
                "Shipper '{0}' successfully updated.",
                e.Keys["ShipperID"]);
        }
        else
        {
            lblMessage.Text = "Unable to successfully update shipper.";
            e.ExceptionHandled = true;
        }
    }

    protected void gvShippers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            TextBox txtCompanyName = gvShippers.FooterRow.FindControl("txtCompanyName") as TextBox;
            TextBox txtPhone = gvShippers.FooterRow.FindControl("txtPhone") as TextBox;

            if (txtCompanyName == null) { return; }
            if (txtPhone == null) { return; }

            sdsShippers.InsertParameters["CompanyName"].DefaultValue = txtCompanyName.Text;
            sdsShippers.InsertParameters["Phone"].DefaultValue = txtPhone.Text;

            sdsShippers.Insert();
        }
    }

    protected void gvShippers_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        if ((e.Exception == null) && e.AffectedRows.Equals(1))
        {
            lblMessage.Text = String.Format(
                "Shipper '{0}' successfully deleted.",
                e.Keys["ShipperID"]);
        }
        else
        {
            lblMessage.Text = "Unable to successfully delete shipper.";
            e.ExceptionHandled = true;
        }
    }

    protected void sdsShippers_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        if ((e.Exception == null) && e.AffectedRows.Equals(1))
        {
            lblMessage.Text = String.Format(
                "Shipper '{0}' successfully added.",
                e.Command.Parameters["@ShipperID"].Value);
        }
        else
        {
            lblMessage.Text = "Unable to successfully add shipper.";
            e.ExceptionHandled = true;
        }
    }

}
Good Luck

Expand and Collapse Div

Filed under: ASP.Net, Javascript — yasserzaid @ 9:28 pm

Try this example:

// Javascript
// Collapse function
//
function showHide(elementid){
    if (document.getElementById(elementid).style.display == ‘block’){
        document.getElementById(elementid).style.display = ‘none’;
    }else{
        document.getElementById(elementid).style.display = ‘block’;
    }
}

// HTML
<a onclick=”jscript:showHide(‘ContentID’)”>click here</a>
<div id=”ContentID” class=”collapse”>Content list</div>

// CSS
.Collapse
{
    display:none;
    font-family:Arial, Helvetica, sans-serif;
    font-size:small;
    font-weight:normal;
    color:Black;
}

Good Luck

Older Posts »

Blog at WordPress.com.