Test Post

Posted on December 22, 2007 - Filed Under Uncategorized | Leave a Comment

This is a test post. affiliate microsoft xbox zune

Training on MOSS

Posted on October 25, 2007 - Filed Under MOSS | Leave a Comment

Currently, I’m undergoing traning for MOSS (Microsoft Office Sharepoint Server 2007).

Hope i could share this beautiful things i’ve learned about MOSS to all of you here….

Exporting data from gridview to excel

Posted on October 19, 2007 - Filed Under Uncategorized | Leave a Comment

Sometimes, we come across to a point where we need to export all items displayed in our gridview to excel spreadsheet or to a csv file for reporting purposes or as an attachements for emails, etc. 

So in our html page, we should have a gridview and a button named grdSample and btnSavetoExcel.

And put the following code in the code behind page…

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            grdSample.DataSource = BindData();
            grdSample.DataBind();
        }
    }

    

private string ConnectionString
    {

        get { return @”Server=localhost;Database=Northwind;
        Trusted_Connection=true”; }

    }

 private DataSet BindData()
    {
        // make the query
        string query = “SELECT * FROM Categories”;
        SqlConnection myConnection = new SqlConnection(ConnectionString);
        SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds, “Categories”);
        return ds;

    }

On page upload, we bind our gridview with the datatable so it will display the proper data on the grid. In this sample,we used the categories table of the Northwind database.

protected void btnSavetoExcel_Click(object sender, EventArgs e)
{
        String filename = “Sample” + DateTime.Now.ToShortDateString()  + “.xls”;
       
        Response.Clear();
 
        Response.AddHeader(”content-disposition”, “attachment; filename=” + filename);
 
        Response.Charset = “”;
 
        Response.ContentType = “application/vnd.xls”;
 
       
        stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
 
        grdSample.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
}

Let’s dissect the code above, to better understand the logic in it.

In the event click of the btnSavetoExcel, we first create the filename for the excel file. In this sample, we created a file named sample_[current short date].xls

Usually, I put a date when naming a filename for easier retrieval and references in the future. But then it up toyou on how you would like to name your file.

Movin on, we then erases any buffered HTML output via the Response.Clear method. By the way, we used the Response object to  send output to the client.

The Response.AddHeader sets the HTML header name to value. While the Response.Charset appends the name of the character set to the content-type header. The character set specifies for the browser on how to display characters.

The ContentType property specifies the HTTP content type for the response. If no ContentType is specified, the default is text/HTML.

Then we Constructs and initializes a new instance of the StringWriter class. This  automatically created and associated with the new StringWriter instance.

The RenderControl will outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. The HtmlTextWriter object in this sample is the htmlWrite.
Since this will output the content back to the server, the form will require the gridview tobe inside an HTML form with runat=server…so if your page is in a contentpage…then you’ll be face with this error..

Error: Control ‘GridView1′ of type ‘GridView’ must be placed inside a form tag with runat=server

The solution for this it to have the next code:

public override void VerifyRenderingInServerForm(Control control)
{
        // Confirms that an HtmlForm control is rendered for the
        //specified ASP.NET server control at run time.
}

For further reading on this error, check this… http://msdn2.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx

Gridview with on row computation part 2

Posted on October 18, 2007 - Filed Under Uncategorized | Leave a Comment

So now we have the HTML page all set [see part 1]…we would like to tweak on our code-behind page to make it function the way we wanted it.

First we would like to show all default values when the page loads up. The default values would be the username for the username column, 0 for rate, weight and score columns.

At the Page load event, we would like to

Gridview with on row computation part 1

Posted on October 3, 2007 - Filed Under ASP.NET | Leave a Comment

On this tutorial, I would like to show you how to create a gridview with on the fly computation per row.

For this project we would need to have a gridview with 5 columns: UserName, rate, weight, score, and edit/update button with delete or cancel button. The username will be fix and will be coming from a database table. While the rate and weight will have a default value of 0 and user can edit it or update it. Score will be the product of  rate and weight, which are user inputs.

So first off, we need to create a gridview.  From the toolbox, you can drag and drop a gridview to your form and name your grid ‘grdComputeScore’.

Or turn to the html source view of your page and paste the following codes:

<asp:GridView ID=”grdComputeScore”
       runat=”server”
       AutoGenerateColumns=”False”
       DataKeyNames=”ID”
       OnRowCancelingEdit=”grdComputeScore _RowCancelingEdit”
       OnRowEditing=” grdComputeScore _RowEditing”
       OnRowUpdating=” grdComputeScore _RowUpdating”
       OnRowDeleting=” grdComputeScore _RowDeleting”>
      <Columns>
                <asp:TemplateField HeaderText=”UserName”>
                          <EditItemTemplate>
                                   <asp:Label Runat=”Server”
                                               Text=’<%# Eval(”UserName”) %>’ 
                                               Width=”100%”/>
                                   <asp:TextBox runat=”server”
                                               ID=”txtUserID” 
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “UserID”) %>’
                                               Visible=”false” />
                         </EditItemTemplate>
                         <ItemTemplate>
                                   <asp:Label Runat=”Server”
                                               Text=’<%# Eval(”Factor”) %>’
                                               Width=”100%”/>
                                   <asp:TextBox runat=”server” 
                                               ID=”txtUserID” 
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “UserID”) %>’
                                               Visible=”false” />
                          </ItemTemplate>
                 </asp:TemplateField>
                 <asp:TemplateField HeaderText=”Rate”>
                         <EditItemTemplate>
                                   <asp:TextBox Runat=”Server”
                                               id=”txtEditRate”
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “Rate”) %>’ 
                                               DataFormatString=”{0:c}”
                                               Width=”80″
                                               Font-Size=”8pt”/>
                                   <asp:CompareValidator runat=”server”
                                               ID=”validateRate”
                                               ValidationGroup=”score”
                                               ControlToValidate=”txtEditRate”
                                               Type=”Double”
                                               Display=”dynamic”
                                               ErrorMessage=”Rate is not a valid value.<br />” />
                         </EditItemTemplate>
                         <ItemTemplate>
                                   <asp:Label Runat=”Server”
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “Rate”) %>’
                                               DataFormatString=”{0:c}”
                                               Width=”100%”/>
                         </ItemTemplate>
               </asp:TemplateField>
              <asp:TemplateField HeaderText=”Weight”>
                         <EditItemTemplate>
                                   <asp:TextBox Runat=”Server”
                                              id=”txtEditWeight” 
                                              Text=’<%# DataBinder.Eval(Container.DataItem, “Weight”) %>’
                                              DataFormatString=”{0:c}”
                                              Width=”80″
                                              Font-Size=”8pt”/>
                                  <asp:CompareValidator runat=”server”
                                              ID=”validateWeight”
                                              ValidationGroup=”Process”
                                              ControlToValidate=”txtEditWeight”
                                              Type=”Double”
                                              Display=”dynamic”
                                              ErrorMessage=”Weight is not a valid value.<br />” />
                         </EditItemTemplate>
                         <ItemTemplate>
                                   <asp:Label Runat=”Server”
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “Weight”) %>’ 
                                               DataFormatString=”{0:c}”
                                               Width=”100%”/>      
                         </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText=”Score”>
                         <EditItemTemplate>
                                  <asp:TextBox Runat=”Server”
                                               id=”txtEditScore”
                                               Text=’<%# DataBinder.Eval(Container.DataItem, “Score”) %>’ 
                                               DataFormatString=”{0:c}”
                                               Width=”80″
                                               Font-Size=”8pt”
                                               Readonly=”true”/>                                                   
                         </EditItemTemplate>
                         <ItemTemplate>
                                <asp:Label Runat=”Server”
                                                Text=’<%# DataBinder.Eval(Container.DataItem, “Score”) %>’
                                               Runat=”Server”
                                               DataFormatString=”{0:c}”
                                              Width=”100%”/>                         
                         </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField>
                         <EditItemTemplate>
                                <asp:Button Runat=”Server”
                                               Text=”Update”
                                               CommandName=”Update”
                                               Font-Size=”7pt”
                                               Width=”35px”/>
                                 <asp:Button Runat=”Server”
                                               Text=”Cancel”
                                               CommandName=”Cancel”
                                               Font-Size=”7pt” 
                                               Width=”35px”/>                                                
                      </EditItemTemplate>
                      <ItemStyle Wrap=”False”></ItemStyle>
                      <ItemTemplate>
                                 <asp:Button Runat=”Server”
                                               Text=”Edit” CommandName=”Edit”
                                               Font-Size=”7pt”
                                               Width=”35px”/>
                                 <asp:Button Runat=”Server”
                                               Text=”Delete” CommandName=”Delete”
                                               Font-Size=”7pt”
                                               Width=”35px”/>                                            
                       </ItemTemplate>
             </asp:TemplateField>
 </Columns>
</asp:GridView>
***************

The html code above creates a gridview with 4 column fields (1) UserName, (2) rate,  (3)weight, (4) score. and two other columns for edit/update and delete/cancel buttons.

As you can see, we have labels for factor as this is going to be a fix item. While the rate, weight and score can be edited, so we have textboxes on edittemplate. But with score, the textbox is set to readonly = true because we would want user to input anything on this. Score wil be the product of weight and rate.

By default, we want the the grid to show all users with their rate and weight = 0. So we will set this on our code behind page which i would be discussing in part 2.

The default value can be edited or updated, we would like to check if user is entering or inputing a correct value. So we need to have on row validation. That is why we have CompareValidators after each textboxes in the  rate and weight to check if values are correct.  If you can see, we dont have CompareValidator after the txtScore because there wont be any user interaction on this.

We also have to set the dataformats for the rate, weight and score to decimal format or to two digit after the period, so we used DataFormatString=”{0:c}”

Welcome

Posted on October 1, 2007 - Filed Under General | Leave a Comment

Hello everyone….

Welcome to my blog space….

Btw, i’ll be sharing mostly about .NET here…sample codes, tutorials, tips, and some hot news as well…

So do standby for the first topic….i’ll be posting it later today….

BNS Hosting - Bitstop, Inc