Monday, 11 September 2017

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView
 

<div id="gridviewDiv">
      
   <asp:GridView ID="gridViewToPrint" runat="server" 
                  DataSourceID="SqlDataSource1">
     <Columns>
    <asp:BoundField DataField="CategoryID" 
                    HeaderText="CategoryID"/>
    <asp:BoundField DataField="CategoryName" 
                    HeaderText="CategoryName"/>
    </Columns>
    </asp:GridView>
   </div>
      
   <asp:Button ID="btnPrint" runat="server" 
               Text="Print GridView Data"/>
 
 
 
 
 
 
 
 
 
 
 
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        string printScript =
        @"function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gridviewDiv');
            var printWindow = window.open('gridview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
        this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
        btnPrint.Attributes.Add("onclick", "PrintGridView();");       
    } 

Basic of MVC in ASP.net

Few Basic Things For Starting Up With ASP.NET MVC







Developing a Web Application by Using ASP.NET MVC 2
■ Structure an ASP.NET MVC application.
■ Create custom routes.
■ Create controllers and actions.
■ Create and customize views.


First  Part(UNDERSTANDING BLOG:What is MVC)

DIFFRENCES With ASP.NET
MVC, you write the model, create the views, and code the controllers; thus you have finer
control over how each request is handled and each response is rendered. With ASP.NET MVC,
there is less “hidden” from you (and thus less work done automatically for you).

ASP.net:
ASP.NET application basic architecture , in
which requests are handled by ASP.NET: it calls your page; it executes your events in order;
those events affect the response; and ASP.NET ultimately returns the response.


MVC
MVC application has a different architecture, page processing model, conventions,
and project structure than an ASP.NET web form site.

MVC Components:
These components should be familiar to you as a web developer. A controller is a class; the
model is either made up of custom classes or generated classes that use the Entity Framework
or LINQ to SQL; and the views are ASPX webpages. The following list provides a more detailed
definition of these components:
Controller often called the connection between the model and the view.



Life Cycle of MVC

1.You add routes to this collection inside the Global.asax file’s
RegisterRoutes method (which is called by Application_Start).

2.These routes are added to the
table when your application starts.

3The request is then mapped to a route, and
RouteData and RequestContext objects are created to represent the route and the request, respectively.

4.Processing of the RequestContext object is then passed to classes in the System.Web.Mvc
namespace.

5.The MvcRouteHandler class handles the routing to your MVC controller class. It
creates an instance of MvcHandler to actually call the controller and run its Execute method.


6.Your controller then uses ControllerActionInvoker to determine which action to run based
on the request.

7.Your action method accepts the user input and prepares a response


ROUTES
You add routes to this collection inside the Global.asax file’s
RegisterRoutes method (which is called by Application_Start).You must know both way
1.by direct RouteTable class
2.RegisterRoutes method

Understanding Routing Basics


Your website can respond to both ASP.NET and ASP.NET MVC requests. If no route is found
for a request, the request passes to ASP.NET for processing.



ASP.Net Website/.NET 4.0
 (add a Global.asax file)

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {

        RouteTable.Routes.MapPageRoute("Department", "Department/CITY/{DeptName}", "~/DepartmentwiseEmployees.aspx");
      RouteTable.Routes.MapPageRoute("Department1",        "Dex/{student_name}", "~/Default3.aspx");
       
    }

</script>





MVC Project/.NET4.0
(you will find a file global.asax with this code) 

using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}


//RegisterAllAreas() call to ensure that the area mapping is carried out.
--------------------------------------------------------------------------------------------------------------------

Either write in RegisterRoutes Method as Above or directly Type   RouteTable.Routes.MapPageRoute













Defining Application Areas
AREA 
(just give you logical ready made structure of folder if you want more folder to hold Controller,Views and model)

You can use the default project structure for most websites without having any problems.
However, there are some sites that are very large; keeping all the models, views, and controllers
in this single folder set can be difficult to manage. For such cases, you can define
different MVC project areas in your application.
An area in ASP.NET MVC is a subset of the project structure based on a logical grouping.
Each area contains area-specific models, views, and controllers. The root of the site contains
the sitewide models, views, and controllers. This type of partitioning can make it easier to
manage your application files.
You create an area in ASP.NET MVC by right-clicking the project and choosing Add | Area.
You give each area a name and Visual Studio generates a separate set of folders for storing
the MVC files in your area.





Explanations With Screenshots

You Must Go Through This At A Glance
Quick Check
1. What is the ASP.NET MVC convention for naming controller classes?
2. What is the ASP.NET MVC convention for storing views?
3. What is the ASP.NET MVC convention for naming views?

Quick Check Answers
1. You name your controller classes after entities in your model and add the
Controller suffix, as in EntityController.
2. A view should be stored in a folder with the same name as the controller (minus
the suffix), as in Entity.
3. A view should be named after the action method in the controller, such as
Index.aspx or Create.aspx.

Didn't Undersand?Ok!

1)GLOBAL.ASAX File

















2.PROJECT FILES SCREENSHOT #1




3.PROJECT FILES SCREENSHOT #2




 4.CONTROLLER CLASS






 5.NAMING DEPENDENCIES OF ALL (you can not name anything to Controller and call it with any function name with any name of view, there are some patterns and way to follow)






1. You name your controller classes after entities in your model and add the Controller suffix, as in EntityController.

2. A view should be stored in a folder with the same name as the controller (minus the suffix), as in Entity.

3. A view should be named after the action method in the controller, such as Index.aspx or Create.aspx.














SQL Server Is Too Busy...

SQL Server Is Too Busy...
Quick Tips and tricks to tackle with performance

What?

Today I will guide to resolve the “server too busy” error in asp.net.

Why?

There are few no of reasons to occur this error. By the word itself, we can under this error is occurred when server unable to handle the requests and go busy out while trying to do so.following could be the response which could be the reason of slow down the server.

1.    QUERY RESPONSE:    The database query may take long time to respond.
2.    IIS RESPONSE:             No of free threads not enough to IIS to handle the request
3.    MEMORY RESPONSE:In your code has memory leaks
4.    LOOP RESPONSE:       In your code have infinite loops.
5.    VISITOR RESPONSE:  Server does not have capabilities to handle huge no of visitors.

Solution?

•    If first one is reason for this error, then you may to review your query using SqlProfiler and fix the query to response quickly.
•    If your code has memory leaks or infinite loops, then you have to review your code and have to fix.
•    The second is most important on for this error. But we can fix this case easily with webconfig file.
When you are take look your web config file, there is a tag call httpRuntime like following normally.
<httpRuntime executionTimeout="3600" maxRequestLength="4096" />
 More details about httpRuntime here
To resolve this error with web config, we have to override the following attributes in config.
1.    executionTimeout
2.    maxRequestLength
3.    minFreeThreads
4.    minLocalRequestFreeThreads



executionTimeout
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. If the debug attribute is True, to help avoiding application shut-down while you are debugging, do not set this time-out to a large value. The default is 110 seconds.
maxRequestLength
Specifies the limit for the input stream buffering threshold, in KB. This limit can be used to prevent denial of service attacks that are caused, for example, by users posting large files to the server. The default is 4096 KB
minFreeThreads
Specifies the minimum number of free threads to allow execution of new requests. ASP.NET keeps the specified number of threads free for requests that require additional threads to complete processing. The default is 8.
minLocalRequestFreeThreads
Specifies the minimum number of free threads that ASP.NET keeps available to allow execution of new local requests. The specified number of threads is reserved for requests that are coming from the local host, in case some requests issue child requests to the local host during processing. This helps to prevent a possible deadlock with recursive reentry into the Web server. The default is 4.
(API definition from MSDN)
Now we have to override values for above attributes. Once override web config file will look followings,
<httpRuntime enableVersionHeader="false" executionTimeout="72000" maxRequestLength="4096" minFreeThreads="72" minLocalRequestFreeThreads="88" useFullyQualifiedRedirectUrl="false" />
 Just override your production web configuration file with above modfied file. Now see your server to able to handle more request than earlier.But your web server does not enough memory or CPU, then you have to upgrade that to support to handle to more request.

Conclusion

In tips I have given solutions to “server too busy” error in asp.net.i hope this is help to you all.

Find Control Under RowCommand

Find Control Under RowCommand


protected void GridViewtemp_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddSchedule")
        {
                pnlschedule.Visible = true;
                lblscheduleforItem.Text = e.CommandArgument.ToString();

                GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
                Label lblDate = (Label)row.Cells[0].FindControl("lblName");
                string teamName = lblDate.Text;
                int rowindex = row.RowIndex;
                lblscheduleforItemName.Text = ((Label)GridViewtemp.Rows[rowindex].FindControl("lblName")).Text;

                      
        }
    }

SQL Transaction In C#,ASP.Net

 Transaction In C#,ASP.Net


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}

catch (Exception Error)
{


}




In above Part the only thing you have to care about is 


SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
  SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
  cmd.ExecuteNonQuery();
  transaction.Commit(); //whenever you call commit it means now finaly
                        //all execution will take place else rollback to catch
}
catch
{
 transaction.Rollback(); 
}

Friday, 26 August 2016

What is Async & Await in C# .net?

What is Async & Await in C# .net?

If you are familiar with normal ASP.net C# code then this would be easy for you to understand.
just see the below code I'll explain it later (don't go with long red arrow)





In above its a simple asp.net web page code behind where someone click the Button1_Click,and then a callprocess() function get called.after this function we add "Program finish" text in a ListBox1.and increment value of a variable val to 10.

Now how do you think the code need to behave.


STEP 1>STEP 2>STEP3

WHAT you assume normally 

1.int val=0 set in top and declared in last of the button click so val>=10 must fail. right?

2.Listbox add item "Program finish" in last but before it, callprocess() method comes which adding a item "Long Process finish" .so ListBox1 must have LongProcessFinsh in top and Programfinish after that .right?


BUT what realy happens?

Let me tell you everything happen exactly opposite of it.

STEP3(as callprocess() is async other code could not wait for it which has await attach to it)>STEP1>STEP2


In callprocess function the condition "if(val>-0" have value 10 in it already.and ProgramFinish is already added in Listbox1 before LongProcessFinish.

Its because we declare await inside a function (await always do a task(your async kind of task))await LongProcess();


and when you added it you must declare that function with async.

        public async void CallProcess()
        CallProcess();//this is detected as async with calling himself await
        this.ListBox1.Items.Add("Program finish");//they executed without wait
        val += 10;                                                           //they execute without wait


so what basicaly async/await/Task doing 


Async:keyword to declare yes this is a async method

Await:this code will execute but telling other code part dont wait for me I am coming from behind.

Task:like void,we perform here our task which return type is 

Void: Means nothing to return

Task: It will perform one operation, a little similar to void but the difference is there.

Task<T>: Will return a task with a T type parameter. (I hope you are familiar with the concept of T)










Monday, 13 June 2016

Deploy Website In IIS (Asp.net)


Deploy Asp.net Website In IIS Local


1.keep your project  in a folder (eg. D://MyProj/Proj1)
2.go to run
3.type inetmgr
4.on server(LEFT SIDE PANEL)  go to sites>default websites
5.right click on default website and add application
6.give any alias(name for ur project)
7.asp.net application poll must be .net framework 4.0
8.in physical path enter path where your project reside.(eg. D://MyProj/Proj1)

9.'default document' is used to set start_page in case user do not provide any page in url (eg. index.html/defalt.aspx)
10.now go on ur website showing in IIS,right click,manage site and browse.

Below are the solutions for few error which often comes out.


1)HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

DO 1: Enable the Directory Browsing feature in IIS (Recommended)
1.    Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
2.    In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
3.    In the Features view, double-click Directory Browsing.
4.    In the Actions pane, click Enable.
If that does not work for, you might be having different problem than just a Directory listing issue. So follow the below step,

ELSE DO 2: Add a default document
To resolve this problem, follow these steps:
•         Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
•         In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
•         In the Features view, double-click Default Document.
•         In the Actions pane, click Enable.
•         In the File Name box, type the name of the default document, and then click OK.

ELSE DO 3: Enable the Directory Browsing feature in IIS Express

Note This method is for the web developers who experience the issue when they use IIS Express.
Follow these steps:
•         Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt: C:\Program Files\IIS Express
•         Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true


2)ASP.Net IIS7: The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis -i


Run above command in cmd (RUN AS ADMINISTRATOR)
which will activate asp.net 4.0 like below





3)Website not accessible from other computer in network





1. Open Windows Firewall with Advanced Security ( or run wf.msc)
2. Open Inbound Rules and find World Wide Web Services (HTTP Traffic-In)
3. Right Click on World Wide Web Services (HTTP Traffic-In) and Enable Rule

Tuesday, 31 May 2016

Creating download link to a file on a file server

For .Net Developer This Might Help You For Creating 
download link to a file on a file server

string strURL;
strURL = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AllFiles\Log\") + "SaleLogFile.log";//name of the file you are picking 
         

            WebClient req = new WebClient();
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.AddHeader("Content-Disposition", "attachment;filename='SaleLogFile.log'");//change downloaded file name
            byte[] data = req.DownloadData(strURL);
            response.BinaryWrite(data);
            response.End();

Tuesday, 14 October 2014

Convert Dataset To EXCEL or NOTEPAD

 Convert Dataset to EXCEL


using System.Xml.Schema;
using System.Xml;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

private void button_Clicked(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        public DataTable ExportToExcel()
        {
            string sql = null;
            string data = null;
            int i = 0;
            int j = 0;

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
          
                             DataSet ds = new DataSet();


             //fill your dataset with any data



                for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                {
                    for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                    {
                        data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                        xlWorkSheet.Cells[i + 1, j + 1] = data;
                    }
                }

                xlWorkBook.SaveAs(@"D:\ESIReports.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
              
               
                 xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                //NOTE PAD file or .CSV FILE CREATION
                CSVNotepad(any);
                MessageBox.Show("Excel file created , you can find the file ESIReport.xls");
                return table;

            }
        }










      



 Convert Dataset to NOTEPAD


 private void button_Clicked(object sender, EventArgs e)
        {
            CSVNotepad(DataTableObj)
        }

 public  void CSVNotepad(DataTable dsa)
        {
            DataTable sourceTable = new DataTable();
            sourceTable = dsa;
    
            using (StreamWriter writer = new StreamWriter(@"D:\ESIReports.txt"))//.txt or .csv
            {
                Rfc4180Writer.WriteDataTable(sourceTable, writer, true);
            }
        }



//REQUIRED CLASS FILE FOR NOTEPAD EXECUTION
    public static class Rfc4180Writer
    {
        public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
        {
            //if (includeHeaders)
            //{
            //    List<string> headerValues = new List<string>();
            //    foreach (DataColumn column in sourceTable.Columns)
            //    {
            //        headerValues.Add(QuoteValue(column.ColumnName));
            //    }

            //    writer.WriteLine(String.Join(",", headerValues.ToArray()));
            //}

            string[] items = null;
            foreach (DataRow row in sourceTable.Rows)
            {
                items = row.ItemArray.Select(o => QuoteValue(o.ToString())).ToArray();
                writer.WriteLine(String.Join(",", items));
            }

            writer.Flush();
        }

        private static string QuoteValue(string value)
        {
            return String.Concat("\"", value.Replace("\"", "\"\""), "\"");
        }
    }

Tuesday, 12 August 2014

Could not find a part of the path 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\


How to get rid from the error "Could not find a part of the path 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\"?

this error is usually coz for .net server a path in a form of string is not enough you have to specify thats you are accessing it from your own server ,you have to tell server that "YES!its a directory of my own server" by implementing Server.MapPath() method.

Lets see how it goes....as i want one of my directory to be removed i am using below code

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

string path="Reports/NK/MyDirectory";//path as a string
          
Directory.Delete(path, true);//wrong way hence shows error

Directory.Delete(Server.MapPath(path), true);//right way as he know its a directory in your own server

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

let me know if you still find any issue.

Monday, 7 July 2014

M S Access Date Between Query Not Giving Desired Result

Actualy what I will do here is just show you
Examples of using dates as criteria in Access queries



If I was not wrong you were facing problem in Access Database Query of Between   or >< 
for Dates

Actualy it is not as same as SQL to get record from by just putting between keyword...

MS Access must be filterd from  format('<urdate'>,'dd/mm/yyyy')

but lets first focus what you are facing /what wrong you were doing...

WRONG METHODS
SELECT Purchase_Date, Purchase_Billno
FROM Purchase_Item
where format('Purchase_Date,'dd/mm/yyyy')> '02/01/2014'
and format('Purchase_Date,'dd/mm/yyyy')<'22/12/2014'



or 

 SELECT Purchase_Date, Purchase_Billno
FROM Purchase_Item
where format('Purchase_Date,'dd/mm/yyyy')> #02/01/2014#
and format('Purchase_Date,'dd/mm/yyyy')<#22/12/2014#



RIGHT WAY
Lets See How Its Works..

SELECT Purchase_Date, Purchase_Billno
FROM Purchase_Item
where Purchase_Date> format('02/01/2014','dd/mm/yyyy')
and Purchase_Date< format('22/12/2014','dd/mm/yyyy')



This will show you the exact match of your desired result,
So Hows that solution :)


Sunday, 6 July 2014

String First And Last Character by Substring in C#

Let say you have a string and you want its first or last character like first 2 or last 4 how could you do that?

here is sample for that


string mystring = "122014";
      
        mystring = mystring.Substring(mystring.Length - 4);
        Response.Write(mystring.ToString());


//output:2014


 mystring = "122014";
        string sub = mystring.Remove(mystring.Length - 4);
        Response.Write("<br>");
        Response.Write(sub.ToString());


//output: 12

Wednesday, 12 June 2013

Add / Change Rdlc at Runtime


Add / Change Rdlc at Runtime

            reportViewer1.LocalReport.EnableExternalImages = true;        
            reportViewer1.LocalReport.ReportEmbeddedResource = "ChequePrint.Report.Report1.rdlc";
            this.DataTable1TableAdapter.Fill(this.ChecqueDetail.DataTable1);
            this.reportViewer1.RefreshReport();


As you'll see in
reportViewer1.LocalReport.ReportEmbeddedResource = "ChequePrint.Report.Report1.rdlc";

ChequePrint.Report.Report1.rdlc is just a text of rdlc file path,and i got it from,







on report viewer click on top right side small button (step 1) and view the report list f




Sunday, 10 February 2013

Working With DateTime In SQL and C#

Date Time Format In C# and SQL







In ASP.net C#

compare two date like TextBoxToDate and TextBoxToDate

DateTime org = DateTime.ParseExact(TextBoxToDate .Text,"dd/MM/yyyy",null);
DateTime enter = DateTime.ParseExact(TextBoxToDate.Text, "dd/MM/yyyy", null);

if(enter.Date<org.Date)
        {
//do what you wish          
        }


       

Monday, 4 February 2013

Selection In GridView With CheckBoxes


CheckBoxes Wise Selection In GridView in just 3 steps







1)In ASPX side
 your grid view must contain DataKeyNames
 and checkbox under templatefield

 <asp:GridView ID="GridViewtemp" runat="server"   DataKeyNames="Person_Id">



2)Now you have above grid where so many rows are avail and each row has a checkbox in it(as we placed a checkbox in templatefield's item template)

now when user click on these checkboxes and make out his selection we will provide him further a button 'btnselect' which will again bind a grid and show you only those selected row which were checked previously.

3)So On that btnselect_click event




In C# On Button Click

 protected void btnselect_Click(object sender, EventArgs e)
     {
       

    
             for (int i = 0; i < GridViewtemp.Rows.Count; i++)
             {
                 if (((CheckBox)GridViewtemp.Rows[i].FindControl("chkSONo")).Checked == true)
                 {
                     soid = ((Label)GridViewtemp.Rows[i].FindControl("
lblPersonid")).Text;


                     if (value == "")
                     {
                         value = soid;
                     }
                     else
                     {
                         value = value + "," + soid;
                     }


                 }

             }
             BindItemGrid(soid);
            
       
     }
     public void BindItemGrid(string Key)
     {
         query = " select * from tb_Stamping  where   [Person_Id] in (" + value + ")";
         SqlDataAdapter adp = new SqlDataAdapter(query, con);
         DataSet ds = new DataSet();
         adp.Fill(ds);
         gvselectcontent.DataSource = ds;
         gvselectcontent.DataBind();

     }

Tuesday, 22 January 2013

Gradient Text Effect or Button CSS Sample

Gradient Texture In Button or Text

If u guys are looking stuff like you want to gradient effect to a text or button .
then below is the simple code without much bugs.











<style>
h1 {
  font-size: 72px;
  background: -webkit-linear-gradient(#eee, #333);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.clr {
  font-size: 72px;
  background: -webkit-linear-gradient(#eee, #333);
  -webkit-background-clip:button;
  -webkit-text-fill-color: transparent;
}

.clrtwist {
  font-size: 72px;
  background: -webkit-linear-gradient(#333,#eee );
  -webkit-background-clip:button;
  -webkit-text-fill-color: transparent;
}</style>


<h1>vijay negi and the gradient!</h1>
    <input id="Button1" class="clr" type="button" value="button" />
        <input id="Button2" class="clrtwist" type="button" value="button" />

below one is the output



Monday, 14 January 2013

SQL Transaction In C#,ASP.Net

 Transaction In C#,ASP.Net
 



SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try
{
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}

catch (Exception Error)
{


}

In above Part the only thing you have to care about is

SqlTransaction transaction;
con.Open();
transaction = con.BeginTransaction();
try {
  SqlCommand cmd = new SqlCommand("insert command....", con,transaction);
cmd.ExecuteNonQuery();
transaction.Commit();                    //whenever you call commit it means now finaly
                                                       //all execution will take place else rollback to catch
}
catch
{
  transaction.Rollback(); 

Thursday, 27 December 2012

Autocomplete Extender AJAX


Alternate use of  AutoComplete Extender AJAX




For searching what we basically need is  name and id behind it.
so for that we must have a
searcher :textbox(txtSearch)
id holder when search complete:hiddenfield(hfCustomerId)


Htmil Source Side


<script type = "text/javascript">

                      function ClientItemSelected(sender, e) {

                          $get("<%=hfCustomerId.ClientID %>").value = e.get_value();

                      }

    </script> 

Search by Client: 

                <asp:HiddenField ID="hfCustomerId" runat="server" />

                <asp:TextBox ID="txtSearch" runat="server" Width="200"></asp:TextBox>

                <asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server" 

                    BehaviorID="AutoCompleteEx" CompletionInterval="100" 

                    CompletionListCssClass="completionList" 

                    CompletionListHighlightedItemCssClass="itemHighlighted" 

                    CompletionListItemCssClass="listItem" CompletionSetCount="20"  OnClientItemSelected="ClientItemSelected"

                    DelimiterCharacters=";, :" EnableCaching="true" MinimumPrefixLength="1" 

                    ServiceMethod="GetClientList" ShowOnlyCurrentWordInCompletionListItem="true" 

                    TargetControlID="txtSearch" UseContextKey="True">

                </asp:AutoCompleteExtender>






Code Behind

Web Method to process autocomplete with textbox



Instead this (used for singal value)



SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ALPHAconnString"]);

        SqlCommand cmd = new SqlCommand("SELECT distinct [Company_Name],Client_id FROM Client where Company_Name like '" + prefixText + "%' ", con); 

        if (con.State == ConnectionState.Closed)

            con.Open();

        cmd.CommandType = CommandType.Text;

        SqlDataReader dr = cmd.ExecuteReader();

       



        while (dr.HasRows)

        {

            while (dr.Read())

            {

                string item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["Company_Name"].ToString(), dr["Client_id"].ToString());

                items.Add(item);



                //items.Add(dr.GetValue(0).ToString());



            }

            dr.NextResult();

        }

        return items.ToArray();







Use this(to hold two value)





SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ALPHAconnString"]);

       
 SqlCommand cmd = new SqlCommand("SELECT distinct 
[Company_Name],Client_id FROM Client where Company_Name like '" + 
prefixText + "%' ", con); 

        if (con.State == ConnectionState.Closed)

            con.Open();

        cmd.CommandType = CommandType.Text;

        SqlDataReader dr = cmd.ExecuteReader();

       



        while (dr.HasRows)

        {

            while (dr.Read())

            {

               
 string item = 
AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["Company_Name"].ToString(),
 dr["Client_id"].ToString());

                items.Add(item);



                //items.Add(dr.GetValue(0).ToString());



            }

            dr.NextResult();

        }

        return items.ToArray();







after searching from textbox ,on any button Click


string clientid= Request.Form[hfCustomerId.UniqueID];











Saturday, 6 October 2012

To Work With GridView In Outside Or Internal Event Of Any Control Except

To Work With GridView In Outside Or Internal Event Of Any Control Except


protected void txtDispQty_TextChanged(object sender, EventArgs e)
    {
 ltTotAmt.Text = "0";
    
        for (int i = 0; i < gvSaleDispatch.Rows.Count; i++)
        {
            if (((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text != "")
            {
                if (Convert.ToDouble(((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text) > Convert.ToDouble(((Label)gvSaleDispatch.Rows[i].FindControl("lblOrdQty")).Text))
                {
                    ((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text = "";
                    CloseWindow = "alert('Dispatch Quantity cant be greater than Ordered Quantity....');";
                    ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
                   
                }
                else if (Convert.ToDouble(((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text) > Convert.ToDouble(((Label)gvSaleDispatch.Rows[i].FindControl("lblAvailStock")).Text))
                {
                    ((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text = "";
                    CloseWindow = "alert('Dispatch Quantity cant be greater than Available Stock....');";
                    ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
                }
                else
                {
                    ((Label)gvSaleDispatch.Rows[i].FindControl("lbltot")).Text = String.Format("{0:0.00}", (Convert.ToDouble(((TextBox)gvSaleDispatch.Rows[i].FindControl("txtDispQty")).Text) * Convert.ToDouble(((Label)gvSaleDispatch.Rows[i].FindControl("lblRate")).Text)));
                    ltTotAmt.Text = String.Format("{0:0.00}", (Convert.ToDouble(ltTotAmt.Text) + Convert.ToDouble(((Label)gvSaleDispatch.Rows[i].FindControl("lbltot")).Text)));
                }
            }

        }
        ltTotPayableAmt.Text = ltTotAmt.Text;
}

Monday, 17 September 2012

Bind DropDown Under GridView

Bind DropDown Under GridView
lets go from basic...



How to bind dropdown?

Normaly We Bind A Drop Downdown In Asp.net Page Like below....
.aspx

<asp:DropDownList ID="DropDownListGroup" runat="server"
DataTextField="GroupNm" DataValueField="GroupID" Height="18px"
style="margin-bottom: 0px" Width="205px">
</asp:DropDownList>

.cs
        SqlDataAdapter adp2 = new SqlDataAdapter("select * from Group", con);
        DataSet ds2 = new DataSet();
        adp2.Fill(ds2);
        DropDownListGroup.DataSource = ds2;
        DropDownListGroup.DataBind();      
        DropDownListGroup.Items.Insert(0, "---Select---");




but in case of Grid View Thing are bit different..
You need to workout in RowDataBound Click Event

1.Bind DropDown Under GridView In Item Template

 if (e.Row.RowType == DataControlRowType.DataRow)
     {

              DropDownList drdList = (DropDownList)e.Row.FindControl("DropDownListGroup");
             SqlDataAdapter adp = new SqlDataAdapter("select * from MST_Group", con);
             DataSet ds = new DataSet();
             adp.Fill(ds);
             drdList.DataSource = ds;
             drdList.DataBind();
             drdList.Items.Insert(0, "---Select---");

             }



2.Bind DropDown Under GridView In EditItem Template

 if (e.Row.RowType == DataControlRowType.DataRow)
     {
        
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
         {

             DropDownList drdList = (DropDownList)e.Row.FindControl("DropDownListGroup");
             SqlDataAdapter adp = new SqlDataAdapter("select * from MST_Group",con);
             DataSet ds = new DataSet();
             adp.Fill(ds);
             drdList.DataSource = ds;
             drdList.DataBind();
             drdList.Items.Insert(0, "---Select---");
         }
     }




3.Bind DropDown Under GridView In Footer Template

  if (e.Row.RowType == DataControlRowType.Footer)
     {

       ((Label)e.Row.FindControl("lblQty")).Text = totqty.ToString();
       TxtTotal.Text = totqty.ToString();
     
     }

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...