Search This Blog

Wednesday, May 22, 2013

Details View Item Inserting



protected void DetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {


        FileUpload FileUploadControl = DetailsView.FindControl("FileUpload1") as FileUpload;
         if (FileUploadControl.HasFile && e.Values["Name"] != null)
        {
            string Name = e.Values["Name"].ToString();
            try
            {
                string FileName = Path.GetFileName(FileUploadControl.FileName);
                string MapPath = "~/Images/" + FileName;
                FileUploadControl.SaveAs(Server.MapPath("~/Images/") + FileName);
                byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(MapPath));
                SqlConnection myConnection;
                string myConnectionString = "Initial Catalog=42HNetDb;Data Source=localhost;Integrated Security=SSPI";
                myConnection = new SqlConnection(myConnectionString);
                string myInsertQuery = "INSERT INTO Client (Name,Logo) Values(@Name,@Logo )";
                SqlCommand myCommand = new SqlCommand(myInsertQuery);
                myCommand.Connection = myConnection;
                myCommand.Parameters.Add("@Name", SqlDbType.NVarChar);
                myCommand.Parameters["@Name"].Value = Name;
                myCommand.Parameters.Add("@Logo", SqlDbType.Image);
                myCommand.Parameters["@Logo"].Value = imgdata;
                myConnection.Open();
                myCommand.ExecuteNonQuery();
                myCommand.Connection.Close();
            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
        else
        {
           string script = "alert('Please Insert all the mandatory Fields');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true); //gets executed properly
        }

Monday, May 20, 2013

How to generate GridView columns dynamically based on user selection?



In case we have to give ability to the user to select the columns that should appear in the GridView, we can follow this approach.

Sometimes due to large number of columns to be displayed on the page in the GridView or give a precise look to the data in GridView, we need to show only those columns in the GridView that is selected by the user. In this article we are going to learn how to dynamically generate GridView columns based on user selection. 


This article has been written based on the question asked in this forum thread.


ASPX Code

<div>

Select column to show in the GridView:<asp:CheckBoxList runat="server" ID="chkFields" DataTextField="Column_name" DataValueField="Column_name" RepeatDirection="Horizontal" RepeatLayout="Flow" />
<p>

<asp:Button ID="btnSub" runat="server" Text="Show" OnClick="ShowGrid" />
</p>
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" AutoGenerateColumns="false" />
</div>
In the above code snippet, we have a CheckBoxList control that lists all the columns of my database table. Apart from this, we have a Show button and a GridView. After selecting the columns from the CheckBoxList control user click on the Show button and accordingly the GridView columns are displayed on the page. Notice that AutoGenerateColumnsproperty is set to false in the GridView.
.NET How to Tips and Tricks comes with hundreds of ASP.NET, ASP.NET AJAX, jQuery,  HTML, CSS and JavaScript Tips and Tricks.

Code behind
    string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)
{
BindTableColumns();
}
} private void BindTableColumns() {
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand cmd = new SqlCommand("sp_columns", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@table_name", "PersonalDetail");
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
chkFields.DataSource = table;
chkFields.DataBind();
}
}
} private void GetData() {
DataTable table = new DataTable();
// get the connection
using (SqlConnection conn = new SqlConnection(_connStr))
{
// write the sql statement to execute
string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId";
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// get the adapter object and attach the command object to it
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
// fire Fill method to fetch the data and fill into DataTable
ad.Fill(table);
}
}
}
// specify the data source for the GridView
GridView1.DataSource = table;// bind the data now
GridView1.DataBind();
} protected void ShowGrid(object sender, EventArgs e) {
foreach (ListItem item in chkFields.Items)
{
if (item.Selected)
{
BoundField b = new BoundField();
b.DataField = item.Value;
b.HeaderText = item.Value;
GridView1.Columns.Add(b);
}
}
this.GetData();
}

Compare two dates in GridView

On Row Data Bound


 DateTimeControl renewalDt = (DateTimeControl)e.Row.FindControl("dtRenewDt");
                    renewalDt.OnValueChangeClientScript = "javascript:ckDates()";


.apsx page


 <script language="javascript" type="text/javascript">

        document.getElementById('<%= lblError.ClientID  %>').innerHTML = "";
        document.getElementById('<%= lblError.ClientID  %>').style.display = "none";

        function ckDates() {
            debugger;
            var rval = true;
            var ErrorMsg = "";
            var objFocus;
            var ItemVal;
            var expDt;
            var renewDt;

            var grids = document.getElementById("<%= gvQatarID.ClientID %>")
            var grid = document.getElementById('<%=gvQatarID.ClientID%>');

            if (grid != null) {

                for (j = 1; j < grids.rows.length; j++) {

                    var text = grid.rows[j].getElementsByTagName("input");

                    for (var i = 0; i < text.length; i++) {
                        if (text[i].type == 'text') {
                            if (i == 4) {
                                expDt = text[i];
                            }
                            else if (i == 6) {
                                renewDt = text[i];
                                if (!IsValidDateFormat(renewDt.value)) {
                                    ErrorMsg = "Date format should be dd/mm/yyyy !";
                                    objFocus = renewDt;
                                    rval = false;
                                }
                                else if (!PreSaveAction(expDt, renewDt)) {
                                    ErrorMsg = "The Renewal Date cannot happen earlier than the Expired Date";
                                    objFocus = renewDt;
                                    rval = false;
                                }
                            }
                        }
                    }
                }
            }

            if (rval == false) {
                document.getElementById('<%= lblError.ClientID  %>').style.display = "block";
                document.getElementById('<%= lblError.ClientID  %>').innerHTML = ErrorMsg;
                objFocus.focus();
            }
            else {
                document.getElementById('<%= lblError.ClientID  %>').innerHTML = "";
                document.getElementById('<%= lblError.ClientID  %>').style.display = "none";
            }
            return rval;

        }

    </script>

Thursday, April 4, 2013

Selecting GridView Row by clicking anywhere on the row


ASPX
<%@ page autoeventwireup="true" codefile="SelectRowWithoutSelectCommand.aspx.cs"
        inherits="GridView_SelectRowWithoutSelectCommand" language="C#" masterpagefile="~/MasterPages/Default.master"
        title="GridView: Select Row Without Select Command" %>
<asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1">
        <asp:label id="Label1" runat="server" />
        <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" datakeynames="ProductID,ProductName"
                datasourceid="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
                style="margin-top: 12px;">
                <columns>
                        <asp:boundfield datafield="ProductID" headertext="ProductID" readonly="True" sortexpression="ProductID" />
                        <asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName" />
                </columns>
        </asp:gridview>
        <asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="<%$ ConnectionStrings:NorthwindConnectionString %>"
                selectcommand="SELECT * FROM [Products]">
        </asp:sqldatasource>
</asp:content>
CODE-BEHIND
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridView_SelectRowWithoutSelectCommand : Page
{
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
                Label1.Text = String.Format("You selected product '{0}'.", GridView1.SelectedDataKey["ProductName"]);
        }

        protected override void Render(HtmlTextWriter writer)
        {
                const string onMouseOverStyle = "this.className='GridViewMouseOver';";
                const string onMouseOutStyle = "this.className='{0}';";
                
                foreach (GridViewRow gvr in GridView1.Rows)
                {
                        gvr.Attributes["onmouseover"] = onMouseOverStyle;
                        gvr.Attributes["onmouseout"] = String.Format(
                                onMouseOutStyle,
                                this.GetRowStyleCssClass(gvr.RowState));
                        gvr.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(
                                GridView1, 
                                String.Concat("Select$", gvr.RowIndex),
                                true);
                }
                
                base.Render(writer);
        }

        private string GetRowStyleCssClass(DataControlRowState state)
        {
                if ((state & DataControlRowState.Edit) > 0)
                {
                        return GridView1.EditRowStyle.CssClass;
                }
                else if ((state & DataControlRowState.Selected) > 0)
                {
                        return GridView1.SelectedRowStyle.CssClass;
                }
                else if ((state & DataControlRowState.Alternate) > 0)
                {
                        return GridView1.AlternatingRowStyle.CssClass;
                }
                else
                {
                        return GridView1.RowStyle.CssClass;
                }
        }
}
STYLESHEET
/* Element Styles */
body{
        background-color: #ffffff;
        color: #000000;
        font: normal normal normal 12px/20px Verdana, Geneva, Arial, Helvetica, sans-serif;
        margin: 10px;
}

pre{
        background: #FFFFB3;
        border: solid 1px blue;
        color: blue; 
        padding:10px; 
        margin: 10px; }
/* DetailsView Styles */
.DetailsView
{
        border: solid 1px #6699cc;
        margin-bottom: 12px;
}
.DetailsViewHeader
{
        background-color: #6699cc;
        color: #ffffff;
        font-size: 125%;
        font-weight: bold;
        text-align: center;
}
.DetailsViewFieldHeader
{
        font-weight: bold;
        text-align: right;
}
.DetailsViewCommandRow
{
        text-transform: lowercase;
}
/* FormView Styles */
.FormView
{
        border: solid 1px #6699cc;
        margin-bottom: 12px;
}       
/* GridView Styles */
.GridView
{
        border: solid 1px #6699cc;
        margin: 0px 0px 20px 0px;
}
.GridViewHeader
{
        background: #6699cc;
        color: #ffffff;
        font-size: 14px;
        font-weight: bold;
        text-align: left;
        vertical-align: bottom;
}
.GridViewRow
{
        background-color: #ffffff;
}
.GridViewAlternatingRow
{
        background-color: #ccffff;
}
.GridViewEditRow
{
        background-color: #f0e68c;
}
.GridViewMouseOver
{
        background-color: #f0e68c;
        cursor: hand;
}
.GridViewSelectedRow
{
        background-color: #f0e68c;
}
.GridViewFooter
{
        background-color: #ffffff;
}
.GridViewPager
{
        background-color: #6699cc;
        color: #ffffff;
        font-size: 14px;
        font-weight: bold;
}

Selecting GridView Row by clicking anywhere on the row

Introduction:
This post shows how to select a GridViewRow by clicking anywhere on the Row. Usually, We need to add a CommandField with Select Button or a ButtonField with Select CommandName to fire SelectedIndexChanged event. In this example, I am adding Onclick attribute for GridViewRow with javascript __doPostBack function to initiate a postback with Select Arguments.
Markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Selecting GridView Row</title>
    <style type="text/css">
        bodyhtml
        {
            font-family: Tahoma;
            font-size: small;
        }
        .Normal
        {
            background-color: #EFF3FB;
            cursor: hand;
        }
        .Normal:Hover.Alternate:Hover
        {
            background-color: #D1DDF1;
            cursor: hand;
        }
        .Alternate
        {
            background-color: White;
            cursor: hand;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
        CellPadding="4" Font-Names="Tahoma" Font-Size="Small" ForeColor="#333333" GridLines="None"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Row">
                <ItemTemplate>
                    <%# Container.DataItemIndex+1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
            <asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
        </Columns>
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>
    <br />
    <asp:Label Text="" ID="lblSelectedRow" runat="server" />
    </form>
</body>
</html>

Description:
We need to add onclick attribute for GridViewRow in RowDataBound and we need to add that attribute only for DataRows.

CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = Enumerable.Range(1, 10).Select(a => new
        {
            ID = a,
            FirstName = String.Format("First Name {0}", a),
            LastName = String.Format("Last Name {0}", a)
        });
        GridView1.DataBind();
    }
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    lblSelectedRow.Text = String.Format("You selected row {0} with {1} {2}",
                                            GridView1.SelectedIndex + 1,
                                            GridView1.SelectedRow.Cells[0].Text,
                                            GridView1.SelectedRow.Cells[1].Text);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //add css to GridViewrow based on rowState
        e.Row.CssClass = e.Row.RowState.ToString();
        //Add onclick attribute to select row.
        e.Row.Attributes.Add("onclick"String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
    }
}

http://forums.asp.net/t/1666327.aspx/1
http://dotnetspeaks.net/post/Selecting-GridView-Row-by-clicking-anywhere-on-the-row.aspx