ASP.NET


<body onkeydown="javascript:if(window.event.keyCode == 13) window.event.keyCode = 9;">

รายละเอียดตามนี้เลยครับ พอดีเอา Webform ไปยิง Barcode แล้ว form auto submit เลยต้องหาวิธีเมื่อ user ยิง barcode แล้วให้เป็น tab ไป control ตัวถัดไปแทน
http://forums.asp.net/t/1088853.aspx?make+enter+key+work+as+tab+

ตาม Link เลยครับ
http://forums.asp.net/t/1519283.aspx

พอเราใช้ popup โดยวิธี response.write css ที่เขียนไว้บนเว็บจะหลุดไป วิธีแก้ให้เขียน popup ตามนี้เลย

string str = string.Format(" window.open('DisplayImage.aspx?DocumentID={0}', 'window','HEIGHT=600,WIDTH=820,top=50,left=50,toolbar=yes,scrollbars=yes,resizable=yes');", id));

ClientScript.RegisterClientScriptBlock(this.GetType(), "popup", str);

ที่มา
http://forums.asp.net/t/1510668.aspx?Response+Write+breaking+CSS

1. GridView to Excel

ตัวอย่างนี้จะได้ Format ของ GridView มาด้วย ถ้ามีรูปอยู่ใน GridView ต้องเป็น Full URL Path ถึงจะ Export รูปออกมาได้ เช่น http://xxx.com/test/pic.png ถ้าเป็น /test/pic.png แบบนี้รูปจะไม่มาด้วย

    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. */
    }

แบบนี้ format ทีเป็น style จะไม่มาด้วย

    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = _contentType;
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        System.Web.UI.HtmlControls.HtmlForm frm = new System.Web.UI.HtmlControls.HtmlForm();
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

2. Copy / Paste
วิธีนี้ใช้ได้โดยครอบส่วนที่ต้องการ Copy โดยใช้ Tag div แล้วให้ user กดที่ button Copy แล้วนำไป Paste ที่ Excel

<input type="button" value="Copy" onclick="window.clipboardData.setData('Text', document.all['MainDiv'].innerHTML)" />

3. Export to CSV
โดยดึงข้อมูลจาก DataTable

    protected void btnExport_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("th-TH");
        DataTable dt = Session["ActualReceive"] as DataTable;
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment;filename=ActualReceiveReport.csv");
        Response.ContentType = "application/vnd.ms-excel";
        string tab = "";
        foreach (DataColumn dc in dt.Columns)
        {
            Response.Write(tab + "\"" + dc.ColumnName + "\"");
            tab = ",";
        }
        Response.Write("\r\n");

        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            int i;
            for (i = 0; i < dt.Columns.Count; i++)
            {
                Response.Write(tab + "\"" + dr[i].ToString().Replace("\"","\"\"") + "\"");
                tab = ",";
            }
            Response.Write("\r\n");
        }
        Response.End();
    }

http://aspalliance.com/
http://www.aspsnippets.com/ มี export -> word, pdf ด้วย
http://mattberseth.com/
http://forums.asp.net/

We often want to have a gridview which selects items based on a dropdownlist. It’s trivial to do this in the VS2005 designer by simply first creating an SqlDataSource with a where clause, then with the sqldatasource wizard, assign the SelectedValue of the dropdownlist to the GridView.

The application running looks like this:

And the page source to do is simply this:

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<script runat=”server”>
</script>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title>Simple GridView With DropDownList Selection</title>
</head>
<body>
    <form id=”form1? runat=”server”>
        <div>
            <asp:DropDownList ID=”DropDownList1? runat=”server” AutoPostBack=”True”>
                <asp:ListItem>Ikura</asp:ListItem>
                <asp:ListItem>Konbu</asp:ListItem>
            </asp:DropDownList><br />
            <asp:SqlDataSource ID=”SqlDataSource1? runat=”server” ConnectionString=”&lt;%$ ConnectionStrings:NorthWindConnectionString %&gt;“
                SelectCommand=”SELECT [ProductName], [UnitsInStock], [UnitsOnOrder] FROM [Alphabetical List of Products] WHERE ([ProductName] = @ProductName2)”>
                <SelectParameters>
                    <asp:ControlParameter ControlID=”DropDownList1? Name=”ProductName2? PropertyName=”SelectedValue”
                        Type=”String” />
                </SelectParameters>
            </asp:SqlDataSource>
            <asp:GridView ID=”GridView1? runat=”server” AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1?>
                 <Columns>
                    <asp:BoundField DataField=”ProductName” HeaderText=”ProductName” SortExpression=”ProductName” />
                    <asp:BoundField DataField=”UnitsInStock” HeaderText=”UnitsInStock” SortExpression=”UnitsInStock” />
                    <asp:BoundField DataField=”UnitsOnOrder” HeaderText=”UnitsOnOrder” SortExpression=”UnitsOnOrder” />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

However, what if you want to have a show all option in your DropDownList? My suggestion is to abandon (somewhat) the visual programming model (or at least that’s the only way I can think of doing it) and add the SelectParameters in the Page_Load event of the page. In addition, to get all the rows to show, I suggest adding the Sql Injection trick which is add an OR to the sql. You can that make the OR always return true, or always return false. I do this by simply passing a 1=@CompareInteger to the Sql that always gets evaluated. Then dynamically set the CompareInteger to 1 or 999. 1 makes all the rows return, 999 forces the evaluation of the ProductName=@ProductName part of the Where clause.

Here is what the application looks like running:

And here is the code that actually does the job.

<%@ Page Language="C#" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            ControlParameter cp =
                new ControlParameter("ProductName",TypeCode.String,"DropDownList1","SelectedValue");
            SqlDataSource1.SelectParameters.Add(cp);

            Parameter p = new Parameter("CompareInteger", TypeCode.Int32);
            p.DefaultValue = "1";
            SqlDataSource1.SelectParameters.Add(p);
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedValue.Equals("(All)"))
        {
            SqlDataSource1.SelectParameters[1].DefaultValue = "1";
        }
        else
        {
            SqlDataSource1.SelectParameters[1].DefaultValue = "999";  // not one
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>DropDownList and GridView with Show All Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            <asp:ListItem Value="(All)"></asp:ListItem>
            <asp:ListItem>Ikura</asp:ListItem>
            <asp: pan style="color: maroon;">ListItem>Konbu</asp:ListItem>
        </asp:DropDownList><br />
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString %>" SelectCommand="SELECT [ProductName], [UnitsInStock] FROM [Alphabetical List of Products] WHERE ([ProductName] = @ProductName OR 1 = @CompareInteger) ORDER BY [ProductName]">
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>

Notice that autopostback is set on the dropdownlist as well as the select change event. That’s it! Give it a try.

http://peterkellner.net/2006/10/14/showallingridviewfromddl/

เจอปัญหาอีกแล้ว… ตอน user กดปุ่ม export ไปเป็น excel ซึ่งใช้เวลานานพอสมควร ก็เลยจะ disable control ไว้ก่อนเผื่อ user กดซ้ำทำให้ excel ที่ create มา close ไม่สมบูรณ์ เลยต้องหาวิธี disable ปุ่ม export ไว้ขณะที่กำลัง postback ค้นหาเจอวิธีนี้ครับดีที่สุด

http://disturbedbuddha.wordpress.com/

Often, we want to disable the control that triggered an asynchronous postback until the postback has completed. This prohibites the user from triggering another postback until the current one is complete.

The Code

First add a ScriptManager to the page, immediately following the <form> tag.

<asp:ScriptManager ID="ScriptManager1" runat="server" />

Then add a Label wrapped in an UpdatePanel. This label will be populated with the date and time on each postback. We’ll also add a Button inside of the UpdatePanel to cause the postback.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="Label1" runat="server" Text="Label" /><br />
        <asp:Button ID="Button1" runat="server" Text="Update Time" OnClick="Button1_Click" />
    </ContentTemplate>
</asp:UpdatePanel>

We’ll also add an UpdateProgress control and associate it with our UpdatePanel just to let the user know that something’s happening.

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
    <ProgressTemplate>
        Loading...
    </ProgressTemplate>
</asp:UpdateProgress>

Next, we’ll add a events in the code-behind to populate the Label and to introduce some latency, simulating a lengthy update to the page.

VB.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Label1.Text = Now.ToString
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    System.Threading.Thread.Sleep(4000)  'Pause for 4 seconds.
End Sub

And finally we’ll add the client-side code to disable our button during the postback. The Javascript disables the button during the beginRequest event of the PageRequestManager and enables it when control has been returned to the browser in the endRequest event. The control causing the postback is returned from the get_postBackElement() method of the BeginRequestEventArgs object which is passed to the function handling the beginRequest event.

Add the follow script after the ScriptManager on the page:

<script type="text/javascript">
    var pbControl = null;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);
    function BeginRequestHandler(sender, args) {
        pbControl = args.get_postBackElement();  //the control causing the postback
        pbControl.disabled = true;
    }
    function EndRequestHandler(sender, args) {
        pbControl.disabled = false;
        pbControl = null;
    }
</script>

And that’s it!

The Complete Source Code:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<!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">
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <script type="text/javascript">
                var pbControl = null;
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.add_beginRequest(BeginRequestHandler);
                prm.add_endRequest(EndRequestHandler);
                function BeginRequestHandler(sender, args) {
                    pbControl = args.get_postBackElement();  //the control causing the postback
                    pbControl.disabled = true;
                }
                function EndRequestHandler(sender, args) {
                    pbControl.disabled = false;
                    pbControl = null;
                }
            </script>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Text="Label" /><br />
                    <asp:Button ID="Button1" runat="server" Text="Update Time" OnClick="Button1_Click" />
                </ContentTemplate>
            </asp:UpdatePanel>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
                <ProgressTemplate>
                    Loading...
                </ProgressTemplate>
            </asp:UpdateProgress>
        </form>
    </body>
</html>

เจอปัญหาเมื่อใช้ DatePicker ใน UpdatePanel เมื่อ Postback แล้ว DatePicker ไม่ทำงานซะงั้น

วิธีแก้ตามนี้เลย…

http://stackoverflow.com

Next Page »