Wednesday, November 30, 2022

String was not recognized as a valid DateTime ASP.NET C#

 this.Text="22/11/2009";


DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);


reference:- https://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy



or


PIPD = DateTime.Now.ToShortDateString();

DateTime PIP = DateTime.ParseExact(PIPD, "dd/MM/yyyy", null);

Foreign key with primary key SQL join query

 SELECT ua.Username, e.UpdatedOn, e.Remarks from icms_UserAccount ua join icms_employee e on e.UpdatedBy = ua.UserID WHERE e.MainID = @MainID AND e.Remarks IS NOT NULL AND e.Remarks <> '';

Group By max SQL

 SELECT cate_id, MAX( book_price)

FROM book_mast GROUP BY cate_id;




Monday, November 28, 2022

ASP.NET C# getdate() with startdate and enddate SQL query

 select * from icms_TransferDrive where DefaultDrive= '1' and StartDate<=getdate() and enddate>=getdate()

Check extensions of file ASP.NET C#

  public bool CheckExtension(FileUpload fp)

        {

            bool status = false;

            string ext = System.IO.Path.GetExtension(fp.PostedFile.FileName).ToString();

            switch (ext)

            {

                case ".doc":

                case ".DOC":

                case ".docx":

                case ".DOCX":

                case ".zip":

                case ".ZIP":

                case ".pdf":

                case ".PDF":

                case ".jpg":

                case ".JPG":

                case ".jpeg":

                case ".JPEG":

                    status = true;

                    break;

                default:

                    status = false;

                    break;

            }

            return status;

        }

        public bool CheckExtensionpdf(FileUpload fp)

        {

            bool status = false;

            string ext = System.IO.Path.GetExtension(fp.PostedFile.FileName).ToString();

            switch (ext)

            {

                case ".pdf":

                case ".PDF":

                    status = true;

                    break;

                default:

                    status = false;

                    break;

            }

            return status;

        }

Hit Counter in ASP.NET C#

   protected void Page_Load(object sender, EventArgs e)

        {

            // Insert Hits

            try

            {

                if (Session["UserID"].ToString() == "")

                {

                    new UserLogs().HitsCounter(Session["UserID"].ToString(), "Hit");

                }

            }

            catch

            {

                new UserLogs().HitsCounter("0", "Anonymous Hit");

            }


        }

How to find online users in ASP.NET C#

 <div class="hidden-print">Users Online: <%=Application["OnlineVisitors"].ToString()%></div>

Gridview init function ASP.NET C#

init function is used for user roles and for allow AutoGenerateEditButton and paging

  protected void GridView1_Init(object sender, EventArgs e)

        {

            try

            {

                if (Session["AccessType"].ToString() == "ReadOnly" || Session["AccessType"].ToString() == "VO")

                {

                    GridView1.AutoGenerateEditButton = false;

                    GridView1.AutoGenerateDeleteButton = false;

                    //GridView1.AllowPaging = false;

                    HyperLink hl = ((HyperLink)GridView1.FindControl("HyperLink1"));

                    hl.Visible = false;

                    GridView1.PageSize = 100;

                }

            }

            catch { }

        }

Friday, November 25, 2022

ASP.NET Grid view hyperlink query string C#

  <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("ID", "add_SanctionedStrength.aspx?sid={0}") %>' Text="Edit"></asp:HyperLink>


aspx.cs

  protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                BindInstitute();

                BindDiscipline();

                Int64 ID = Convert.ToInt64(Request.QueryString["sid"]);

                if (ID > 0)

                {

                    UpdateFlag = true;

                    sid = ID;

                    BindSanctionedStrength(ID);

                    ViewState["SID"] = sid;

                }

                else

                {

                    ViewState["SID"] = 0;

                    UpdateFlag = true;

                }

            }

Thursday, November 24, 2022

try catch with throw exception ASP.NET C#

  try

                {

                    SmtpClient sc = new SmtpClient();

                    //sc.Host = "10.100.7.111";

                    sc.Host = "10.100.3.109";


                    sc.Port = 25;

                    //sc.Credentials = new System.Net.NetworkCredential("", "");

                    //-- sc.EnableSsl = false;

                    sc.Send(mm);

                    //return true;

                }

                catch (Exception ex)

                {


                    throw new Exception("Mail has not send successfully " + ex.ToString());

                   // return false;

                }

Binding of Data to Textboxes by clicking on button ASP.NET C#

 {

 ddlPnlCadreType.DataSource = Repository.GetCadreType();

                ddlPnlCadreType.DataTextField = "CadreType";

                ddlPnlCadreType.DataValueField = "CadreTypeID";

                ddlPnlCadreType.DataBind();

BindEmployee(id, "", true);

}


 private void BindEmployee(long ID, String DOR, bool Approved)

        {

          


            SqlParameter[] param = { new SqlParameter("ID", ID) };

            DataTable dt = new DataAccess().Read("read_employeebyid", param).Tables[0];

            ViewState["ID"] = ID;

            ViewState["MainID"] = dt.Rows[0]["MainID"].ToString(); ;

            //string Institute = dt.Rows[0]["Institute"].ToString();

            //ddlInstitute.SelectedIndex = ddlInstitute.Items.IndexOf(ddlInstitute.Items.FindByText(Institute));

            ddlPnlCadreType.SelectedValue = dt.Rows[0]["CadreTypeID"].ToString();

            ddlPnlPreviousOrganization.SelectedValue = dt.Rows[0]["PreviousOrganization"].ToString();


            //String Discipline = dt.Rows[0]["Discipline"].ToString();

            //ddlDiscipline.SelectedIndex = ddlDiscipline.Items.IndexOf(ddlDiscipline.Items.FindByText(Discipline));



            ddlPnlDiscipline.SelectedValue = dt.Rows[0]["DisciplineID"].ToString();

            ddlPnlAdjustedDiscipline.SelectedValue = dt.Rows[0]["AdjustedDisciplineID"].ToString();


            ddlPnlTitle.SelectedValue = dt.Rows[0]["Title"].ToString();

            txtPnlName.Text = dt.Rows[0]["Name"].ToString();

            txtPnlFMSID.Text = dt.Rows[0]["FMSID"].ToString();


            ddlPnlGender.SelectedValue = dt.Rows[0]["Gender"].ToString();

            ddlPnlCategory.SelectedValue = dt.Rows[0]["Category"].ToString();

            ddlPnlRosterCategory.SelectedValue = dt.Rows[0]["RosterCategory"].ToString();

            txtPnlDob.Text = dt.Rows[0]["DOB"].ToString();

            txtPnlApointmentDate.Text = dt.Rows[0]["AppointmentDate"].ToString();


            ddlPnlDesignation.SelectedValue = dt.Rows[0]["PresentDesignationID"].ToStri

Logs in ASP.Net C#

  protected void btnDelete_Click(object sender, EventArgs e)

        {

            this.DeleteRecord(Convert.ToInt32(ViewState["ID"]));

            // Insert Operation Logs


            new UserLogs().InsertLog(Session["UserID"].ToString(), "User Deletion");

            

            string messageType = "Success";

            String message = "Successfully deleted...";

            ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + message + "','" + messageType  + "');", true);

            

        }

or on Insert Login click

protected void btnLogin_Click(object sender, EventArgs e)

        {

new UserLogs().InsertLog("Login", param);

}

UserLogs.cs will be find on below link:-

https://drive.google.com/file/d/1bq-OMZMfMbV1HEtGZ2MkK-G78xqDEvl0/view?usp=share_link

Wednesday, November 23, 2022

ASP.NET C# ajaxToolkit Updatepanel with Progress bar Syntax

<style>

.divWaiting {

            position: fixed;

            background-color: #FAFAFA;

            z-index: 2147483647 !important;

            opacity: 0.8;

            overflow: hidden;

            text-align: center;

            top: 0;

            left: 0;

            height: 100%;

            width: 100%;

            padding-top: 20%;

        }

</style>

 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    

    <asp:UpdatePanel runat="server" ID="upPopUps" UpdateMode="Always">

        <ContentTemplate>

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="ID,MainID" OnRowDataBound="GridView1_RowDataBound" CssClass="table table-hover table-bordered table-responsive" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="20" FirstPageText="First" PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" AllowSorting="True" OnRowDeleting="GridView1_RowDeleting" OnInit="GridView1_Init" OnRowCommand="GridView1_RowCommand" OnSelectedIndexChanged="OnSelectedIndexChanged">

----------------

</asp:GridView>


 <asp:Panel runat="server" ID="pnlAddEdit" CssClass="modal-fade" Style="height: 80vh; overflow-y: auto;" BorderStyle="Double" Font-Size="Small">

</asp:Panel>

<asp:LinkButton ID="lnkFake" Text="" runat="server"></asp:LinkButton>


            <ajaxToolkit:ModalPopupExtender ID="popup" BehaviorID="popup" runat="server" DropShadow="false"

                PopupControlID="pnlAddEdit" TargetControlID="lnkFake" BackgroundCssClass="modalBackground" CancelControlID="btnPnlClose">

            </ajaxToolkit:ModalPopupExtender>

        

          </ContentTemplate>

        <Triggers>

            <%--<asp:PostBackTrigger ControlID="GridView1" />

            <asp:PostBackTrigger ControlID="btnPnlDelete" />

            <asp:PostBackTrigger ControlID="btnPnlUpdate" />--%>

        </Triggers>



    </asp:UpdatePanel>

        <asp:UpdateProgress ID="updprogress" runat="server" DisplayAfter="0" AssociatedUpdatePanelID="upPopUps">

                   <ProgressTemplate>

                    <div class="divWaiting">

                         

                            <asp:Label ID="lblWait" runat="server" Text=" Please wait... " />

                            <asp:Image ID="imgWait" runat="server" ImageUrl="~/Content/images/refresh.gif"    />

                        

                        </div>

                   </ProgressTemplate>

            </asp:UpdateProgress>

</asp:Content>


-----------------

Note: Also where you want no autopostback in page, than you have to add that controls inside update panel.   Also we can comment the triggers. It will work as asyncpost.


reference:- https://stackoverflow.com/questions/12191436/how-i-can-use-the-updateprogress-control-to-show-a-wait-symbol

Gridview with more than 8 columns scroll ASP.NET C# - Vertical scroll

 <div style="overflow:scroll">

        <asp:GridView runat="server" ID="gv1">

        </asp:GridView>

</div>

Tuesday, November 22, 2022

Jquery datepicker inside update panel of Grid view ajax

 If Jquery datepicker not working inside Gridview , than use

function pageLoad() {

$(function () {

                $("#txtRetirementDate").datepicker({

                    changeMonth: true,

                    changeYear: true

                });

            });

}


function pageLoad() and plcae datepicker function inside that function

reference:- https://www.codeproject.com/Questions/1123611/Datetime-picker-not-working-inside-update-panel-af


---------------------


Also we can create jquery datepickwer by below code:- 

<script>

$(function () {

                $("#txtDob").datepicker({

                    changeMonth: true,

                    changeYear: true

                });

            });

</script>

aspx page

 <asp:TextBox ID="txtDob" ClientIDMode="Static" runat="server" Text='<%# Bind("DOB") %>'></asp:TextBox>

HTML tags and asp tags minor difference

 asp tag will be used without closing ta eg:- />


but html tags will be always having close tags

example

<button> </button>

if you use <button /> it will show error

Difference between AsyncPostBackTrigger and PostBackTrigger inside asp:updatepanel

 <Triggers>

            <asp:PostBackTrigger ControlID="btnPnlDelete" />

            <AsyncPostBackTrigger ControlID="btnPnlDelete" />

        </Triggers>

------------------

AsyncPostBackTrigger will not refresh the page.


PostBackTrigger will refresh the page.


Monday, November 21, 2022

Bootstrap 5 alert notification - asyncpostback (without refreshing a page button click)

<script type="text/javascript">

        function ShowMessage(message, messagetype) {

            debugger;

            var cssclass;

            switch (messagetype) {

                case 'Success':

                    cssclass = 'alert-success'

                    break;

                case 'Error':

                    cssclass = 'alert-danger'

                    break;

                case 'Warning':

                    cssclass = 'alert-warning'

                    break;

                default:

                    cssclass = 'alert-info'

            }

            $('#alert_container').append('<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert fade in ' + cssclass + '"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>' + messagetype + '!</strong> <span>' + message + '</span></div>');


          //$("#alert_div").fadeTo(5000, 1000).slideUp(1000, function () {

              //  $("#alert_div").slideUp(1000);

        //});

         

        }


aspx.cs page code

 protected void btnPnlUpdate_Click(object sender, EventArgs e){

       try {  string messageType = "Success";

                String message = "Successfully Updated...";

                ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + message + "','" + messageType + "');", true);

}

 catch(Exception ex)

            {

                string messageType = "Error";

                String message = "Mail has not send successfully.";

                //dvMsg.Visible = true;dvMsg.InnerHtml = "dfdfdf";

                lblMsg.Text = "This is notification message demo";



                ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + message + "','" + messageType + "');", true);

            }

}

 https://mdbootstrap.com/docs/b4/jquery/javascript/notifications/

Bootstrap 3 alert with auto hide with ASP.NET C#

 <script>

        function ShowMessage(message, messagetype) {

            var cssclass;

            switch (messagetype) {

                case 'Success':

                    cssclass = 'alert-success'

                    break;

                case 'Error':

                    cssclass = 'alert-danger'

                    break;

                case 'Warning':

                    cssclass = 'alert-warning'

                    break;

                default:

                    cssclass = 'alert-info'

            }

            $('#alert_container').append('<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert fade in ' + cssclass + '"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>' + messagetype + '!</strong> <span>' + message + '</span></div>');


            $("#alert_div").fadeTo(5000, 1000).slideUp(1000, function () {

                $("#alert_div").slideUp(1000);

            });

        }

</script>


aspx page

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <asp:UpdatePanel runat="server" ID="upPopUps" UpdateMode="Conditional">

        <ContentTemplate>

             <div class="messagealert" id="alert_container">

        </ContentTemplate>

  </asp:UpdatePanel>

</asp:Content>


aspx.cs

 protected void btnDelete_Click(object sender, EventArgs e)

        {

            this.DeleteRecord(Convert.ToInt32(ViewState["ID"]));

            // Insert Operation Logs


            new UserLogs().InsertLog(Session["UserID"].ToString(), "User Deletion");

            

            string messageType = "Success";

            String message = "Successfully deleted...";

            ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + message + "','" + messageType  + "');", true);

            

        }

reference:- https://www.webcodeexpert.com/2015/10/how-to-show-animated-bootstrap-alert.html

http://jsfiddle.net/g1rnnr8r/2/

https://www.aspsnippets.com/questions/191634/Bootstrap-alert-message-from-Server-Side-in-ASPNet/


https://stackoverflow.com/questions/23101966/bootstrap-alert-auto-close

Ajax toolkit error - Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Input string was not in a correct format.

 Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Input string was not in a correct format.


If you get the above error, please add command argument in link button of grid


 <asp:TemplateField HeaderText="Modify" Visible="true">

                <ItemTemplate>

                    <asp:LinkButton ID="lnkModify" runat="server" CssClass="btn btn-danger" CommandName="Modify"

                        ToolTip="modify"  CommandArgument='<%# Eval("ID")%>' > Modify</asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>

Ajax toolkit error - Uncaught TypeError: Cannot read properties of null (reading 'parentNode') at Sys.Extended.UI.ModalPopupBehavior._createDomElements

 Uncaught TypeError: Cannot read properties of null (reading 'parentNode')

    at Sys.Extended.UI.ModalPopupBehavior._createDomElements


if you find above error, than you have added visible property in panel to false.


<asp:panel runat="server" ID="pnlAddEdit"  CssClass="modal-fade" style="height: 80vh;overflow-y: auto;" BorderStyle="Double" Font-Size="Small" Visible="false">


Delete visible = 'false' property

Ajax toolkit error - Uncaught Sys.ArgumentNullException: Sys.ArgumentNullException: Value cannot be null. Parameter name: element

 Sys.ArgumentNullException: Sys.ArgumentNullException: Value cannot be null.

Parameter name: element


If you get error in console window in javascript. This is due to below code:-

<ajaxToolkit:ModalPopupExtender ID="popup" BehaviorID="popup" runat="server" DropShadow="false"

PopupControlID="pnlAddEdit" TargetControlID = "lnkFake" BackgroundCssClass="modalBackground" CancelControlID="btnjj" >

</ajaxToolkit:ModalPopupExtender>


You have not declare button for CancelControlID or btn name is wrong.

Friday, November 18, 2022

Popup model ASP.NET C# With Bootstrap class with ajaxToolkit ModalPopupExtender

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <asp:UpdatePanel ID="upPopUps" runat="server" UpdateMode="Conditional">

        <ContentTemplate>

   

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="ID,MainID" OnRowDataBound="GridView1_RowDataBound" CssClass="table table-hover table-bordered table-responsive" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="20" FirstPageText="First" PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" AllowSorting="True" OnRowDeleting="GridView1_RowDeleting" OnInit="GridView1_Init" OnRowCommand="GridView1_RowCommand" OnSelectedIndexChanged="OnSelectedIndexChanged">

      

Linkbutton Hyperlink grid edit to other page ASP.NET C# - Passing ID to edit or delete button grid

 <asp:HyperLink ID="lnkModify" CssClass="btn btn-danger" runat="server" NavigateUrl='<%# Eval("ID", "newEmployee.aspx?ID={0}") %>' Text="Mofify"></asp:HyperLink>


------------------------------------------------

 <asp:LinkButton ID="LinkDelete" runat="server" CausesValidation="False" CommandArgument='<%# Eval("ID")%>' CommandName="Delete" Text="Delete"></asp:LinkButton>



CommandArgument='<%# Eval("ID")%>'    always in single quottes.

Thursday, November 17, 2022

Grid OnRowCommand and OnSelectedIndexChanged difference ASP.NET C#

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="ID,MainID" OnRowDataBound="GridView1_RowDataBound" CssClass="table table-hover table-bordered table-responsive" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="20" FirstPageText="First" PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" AllowSorting="True" OnRowDeleting="GridView1_RowDeleting" OnInit="GridView1_Init" OnRowCommand="GridView1_RowCommand" OnSelectedIndexChanged="OnSelectedIndexChanged">


<Columns>

 <asp:TemplateField HeaderText="Block/Unblock" Visible="true">

                <ItemTemplate>

                    <asp:LinkButton ID="ib_block" runat="server" CssClass="btn btn-danger" CommandName="select"

                        ToolTip="Block/Unblock"> Block</asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>

</Columns>

</asp:Gridview>

Grid init function ASP.NET C#

  protected void GridView1_Init(object sender, EventArgs e)

        {

            try

            {

                if (Session["AccessType"].ToString() == "ReadOnly" || Session["AccessType"].ToString() == "VO")

                {

                    GridView1.AutoGenerateEditButton = false;

                    GridView1.AutoGenerateDeleteButton = false;

                    //GridView1.AllowPaging = false;

                    HyperLink hl = ((HyperLink)GridView1.FindControl("HyperLink1"));

                    hl.Visible = false;

                    GridView1.PageSize = 100;

                }

            }

            catch { }

        }

Master page with two content Place Holder ASP.NET C#

Master page


 <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="cms.Master.cs" Inherits="cadre_mgmt_system.Site1" %>

<%@ Register Src="~/usercontrol/footer.ascx" TagPrefix="uc1" TagName="footer" %>

<%@ Register Src="~/usercontrol/header.ascx" TagPrefix="uc1" TagName="header" %>

<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>ICAR Cadre Management System</title>

    <style>

        body {

            margin: 0px !important;

            padding: 0px !important;

        }


        .header {

            height: 80px;

            line-height: 80px !important;

        }


        .height {

            height: 80px;

        }


        .w3-lobster {

            font-family: "Lobster", serif !important;

        }

Wednesday, November 16, 2022

Group By with count LINQ ASP.NET C#

/var disciplineCount = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g)=> new { discipline = key, disciplinecount = g.Count() }).ToList();


if((disciplineCount.Exists(d => d.discipline == DataBinder.Eval(e.Row.DataItem, "Discipline").ToString() && d.disciplinecount > 1)))

{


}

Tuesday, November 15, 2022

SOAP VS Restful

 Representational State Transfer supports xml, JSON

XML, JSON, Plain text, HTML


soap support only xml

How to check graphic cards in windows

> Press Window + R

> Write dxdiag and click on system tab

select and where query difference LINQ ASP.NET C# - with model or entity

 Select is mapping, we want to select two columns from five. (select columns) gives all rows

where will select all the columns but gives the rows with that values. (select rows) gives all columns


example:-

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
    .Select(x => new { x.EMAIL, x.ID });
reference:-https://stackoverflow.com/questions/6772267/linq-syntax-selecting-multiple-columns


 Where ~= Filter


select  = map the selected column



select for columns     and where for rows.

AND OR operator in Exists function LINQ - ASP.NET C# - without model or entity

var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => DateTime.ParseExact(s.Field<string>("PresentInstitutePostingDate") == ""?"01/01/1990": s.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)).First()).Select(t=> new { PresentInstitutePostingDate = (DateTime.ParseExact(t.Field<string>("PresentInstitutePostingDate") == "" ? "01/01/1990" : t.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)), Discipline= t.Field<string>("Discipline") });

                var tt = final.ToList();

  if (tt.Exists(o => o.PresentInstitutePostingDate == DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture) && o.Discipline == DataBinder.Eval(e.Row.DataItem, "Discipline").ToString()))

                    {

                        e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                    }

Group By max date with empty values(date) LINQ Grid change color of row - ASP.NET C# - without model or entity

  var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => DateTime.ParseExact(s.Field<string>("PresentInstitutePostingDate") == ""?"01/01/1990": s.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)).First()).Select(t=> new { PresentInstitutePostingDate = (DateTime.ParseExact(t.Field<string>("PresentInstitutePostingDate") == "" ? "01/01/1990" : t.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)), Discipline= t.Field<string>("Discipline") });

                var tt = final.ToList();

                if (!string.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate"))))

                {

                    DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).Date.ToString("D");

                    if (tt.Exists(o => o.PresentInstitutePostingDate == DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture) && o.Discipline == DataBinder.Eval(e.Row.DataItem, "Discipline").ToString()))

                    {

                        e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                    }

                }

Linq compare two columns with Exists in List - ASP.NET C# -without model or entity

 var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => DateTime.ParseExact(s.Field<string>("PresentInstitutePostingDate") == ""?"01/01/1990": s.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)).First()).Select(t=> new { PresentInstitutePostingDate = (DateTime.ParseExact(t.Field<string>("PresentInstitutePostingDate") == "" ? "01/01/1990" : t.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)), Discipline= t.Field<string>("Discipline") });

                var tt = final.ToList();

                if (!string.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate"))))

                {

                    DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).Date.ToString("D");

                    if (tt.Exists(o => o.PresentInstitutePostingDate == DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture) && o.Discipline == DataBinder.Eval(e.Row.DataItem, "Discipline").ToString()))

                    {

                        e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                    }

                }

Linq select query ASP.NET C# - select two columns

 var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => DateTime.ParseExact(s.Field<string>("PresentInstitutePostingDate") == ""?"01/01/1990": s.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)).First()).Select(t=> new { PresentInstitutePostingDate = (DateTime.ParseExact(t.Field<string>("PresentInstitutePostingDate") == "" ? "01/01/1990" : t.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)), Discipline= t.Field<string>("Discipline") });

var tt = final.ToList();

if (!string.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate"))))

                {

                    DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).Date.ToString("D");

                    if (tt.Exists(o => o.PresentInstitutePostingDate == DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture) && o.Discipline == DataBinder.Eval(e.Row.DataItem, "Discipline").ToString()))

                    {

                        e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                    }

                }


reference:- https://www.aspsnippets.com/Articles/SELECT-multiple-columns-from-DataTable-using-LINQ-in-C-and-VBNet.aspx

Grid rowdatabound event Find control ASP.NET C# - Creating control - enable or disable control

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

 Label lblDiscipline = ((Label)e.Row.FindControl("lblDiscipline"));



((DropDownList)e.Row.FindControl("ddlTitle")).Enabled = false;

}

Get date from datetime ASP.NET C#

 DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).Date.ToString("d");



reference:- https://stackoverflow.com/questions/7740458/extract-the-date-part-from-datetime-in-c-sharp

Group by with max date ASP.NET C# LINQ - without model or entity

  var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => DateTime.ParseExact(s.Field<string>("PresentInstitutePostingDate") == ""?"01/01/1990": s.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)).First()).Select(t=> DateTime.ParseExact(t.Field<string>("PresentInstitutePostingDate") == "" ? "01/01/1990" : t.Field<string>("PresentInstitutePostingDate"), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture));

                var tt = final.ToList();

                if (!string.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate"))))

                {

                    if (tt.Exists(o => o == DateTime.ParseExact(DataBinder.Eval(e.Row.DataItem, "PresentInstitutePostingDate").ToString(), "mm/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)))

                    {

                        e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                    }

                }

Monday, November 14, 2022

HTML Color codes

 https://htmlcolorcodes.com/

Grouping with Max Linq ASP.NET C# - without model or entity

  var dt = GridView1.DataSource as DataTable;

                var a= dt.AsEnumerable().GroupBy(s => s.Field<string>("Discipline").ToString());

                

                

                //dt.DefaultView.Sort = sort;

                var final = dt.AsEnumerable().GroupBy(x => x.Field<string>("Discipline"), (key, g) => g.OrderByDescending(s => s.Field<Int64>("ID")).First()).Select(t=>t.Field<Int64>("ID"));

                var tt = final.ToList();

                

                if(tt.Exists(o=> o == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "ID"))))

                        {

                    e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                }


reference:-https://stackoverflow.com/questions/35170408/linq-how-to-get-the-max-id-with-a-group-by-clause

Find single number in Array ASP.NET C# - returns boolean

 var tt = final.ToList();

                

                if(tt.Exists(o=> o == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "ID"))))

                        {

                    e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#0000ff");

                }



reference:- https://www.geeksforgeeks.org/c-sharp-check-if-an-array-contain-the-elements-that-match-the-specified-conditions/

How to convert ASP.NET grid datasource to datatable C# - grid data copy

  var dt = GridView1.DataSource as DataTable;

ASP.NET Ajax autocomplete extender

aspx page


  <div class="dropdown col-md-2">

            <asp:TextBox runat="server" ID="txtSearchByName" CssClass="col-md-12 form-control input-sm"></asp:TextBox>

            <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtSearchByName"

                CompletionSetCount="10" CompletionInterval="100" MinimumPrefixLength="3" ServiceMethod="getData">

            </ajaxToolkit:AutoCompleteExtender>

        </div>





aspx.cs page


 [System.Web.Script.Services.ScriptMethod()]

        [System.Web.Services.WebMethod]

        public static List<string> getData(string prefixText, int count)

        {

            return getAdvanceSearchAutocompleteData(prefixText, count);

        }

        public static List<string> getAdvanceSearchAutocompleteData(string prefixText, int count)

        {

            List<string> Name = new List<string>();

            SqlParameter[] param = { new SqlParameter("prefix", prefixText) };


            DataTable dt = new DataAccess().Read("autosuggest_name", param).Tables[0];

            foreach (DataRow dr in dt.Rows)

            {

                Name.Add(dr["Name"].ToString());

            }

            return Name;

        }


Bootstrap dropdown with label with row

<div class="row">

 <div class="col-md-1">Discipline (Select)</div>

        <div class="col-md-2">

            <asp:DropDownList runat="server" ID="ddlDisciplines" CssClass="col-md-12 form-control input-sm"></asp:DropDownList>

        </div>

</div>

we can increase the width by changing the class col-md-1 to col-md-2 or col-md-3

or decrease by col-md-5 to col-md-2

Friday, November 11, 2022

Grouping with max in linq ASP.NET

 var ProcessAudList = ProcessAudService.Where(x => x.Active == "Y")

.GroupBy(x => x.ProjectSeq, (key,g)=>g.OrderByDescending(e=>e.ProjectValue).First());