Monday, December 7, 2009

ASP.NET - display records to grid view

Reference:

http://www.codersource.net/asp_net_grid_view_whidbey.aspx

Below is an example of using C#/ASP.NET to display content to a gridview (need to specify the object of "GridView1" in design view of ASP.NET first):

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

public void BindData()
{ // local variables
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
conn = new SqlConnection("server=xxx;User ID=xxx;Password=xxx");
conn.Open();

cmd = new SqlCommand("select top(100) xxxx", conn);

SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);

GridView1.DataSource = myDataSet;
GridView1.DataBind();

if (conn != null)
{
conn.Close(); conn = null;
}
}
catch (Exception ex)
{
if (conn != null)
{
conn.Close(); conn = null;

strLog = "[ (!!!Fail) Error=" + ex.Message + "]";
Response.Write(strLog);

}
}

Use code as below to add horizontal scrolling


// add code of GridView here


Use code as below to edit content of a row
1. Define functions


2. Function of Edit:

protected void GridView_MatchingServer_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView_MatchingServer.EditIndex = e.NewEditIndex;
BindData();
}

3. Function of Update
Add code as below to retrieve content of field being edited.

GridViewRow row = GridView_MatchingServer.Rows[e.RowIndex];
strMess1 = ((TextBox)(row.Cells[1].Controls[0])).Text; // RecID
strMess2 = ((TextBox)(row.Cells[3].Controls[0])).Text; // content of field

Where Cells[1] and Cells[3] represent the 1st and 3rd columns.

Sunday, December 6, 2009

ASP.NET - save content as ,excel file

Below is an example which indicates how to save content to excel file. It will pop-up a window to ask user to specify proper directory to store the file.

protected void Button1_Click(object sender, EventArgs e)
{
// make sure nothing is in response stream
Response.Clear();
Response.Charset = "";

// set MIME type to be Excel file.
Response.ContentType = "application/vnd.ms-excel";

// add a header to response to force download (specifying filename)
Response.AddHeader("Content-Disposition", "attachment; filename=\"MyFile.xls\"");

// Send the data. Tab delimited, with newlines.
Response.Write("Col1\tCol2\tCol3\tCol4\n");

Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");

// Close response stream.
Response.End();
}

Thursday, December 3, 2009

SQL - Encryption / decryption

Today find a web page which provides example about usage of symmetric and asymmetric for SQL encryption:

http://www.mssqltips.com/tip.asp?tip=1886&home