2009/02/13

A simple way to show a popup window

This is what I use:
private static void ShowMessage(Page page, string message)
{
ScriptManager.RegisterClientScriptBlock(page, page.GetType(),
"IncorrectDate", @"<script>alert('" + message + "');</script>", false);
}
Here is how to use:
protected void btnSave_Click(object sender, EventArgs e)
{
//....
ShowMessage(this, "Success!");
}

PS:Your WebForm must support ASP.Net AJAX (your page must have ScriptManager).

2009/01/25

C#: How to load Excel (xls) and Access (mdb) files (updated: 2012.07.25)

Here is how I load the excel and access files:
1.Includes the name space
using System.Data.OleDb;
2.Set up the connection string
//for xls
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog1.FileName + @";Persist Security Info=True;Extended Properties=EXCEL 8.0";
//for mdb
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openFileDialog1.FileName + @";Persist Security Info=True";
3.Get the schema
private void GetSchemaTable()
{
  try
  {
    //mdb and xls needs OleDbConnection class, not SqlConnection.
    using (OleDbConnection conn = new OleDbConnection(ConnectionString))
    {
      conn.Open();
      //Fetch all tables' schema. This line is the key point of this method.
      DataTable schemaTable =
        conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

      //Fetch all tables' name and assign them to comboBox1.
      foreach (DataRow dr in schemaTable.Rows)
      {
        comboBox1.Items.Add(dr[2]);
      }
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}
4.Load table contents
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  try
  {
    using (OleDbConnection conn = new OleDbConnection(ConnectionString))
    {
      if (String.Equals(FileExtName, "xls"))
        SelectCommand = "SELECT * FROM [" + comboBox1.SelectedItem.ToString() + "]";
      else if (String.Equals(FileExtName, "mdb"))
        SelectCommand = "SELECT * FROM " + comboBox1.SelectedItem.ToString();

      OleDbDataAdapter da = new OleDbDataAdapter(SelectCommand, conn);
      DataTable dt = new DataTable();
      da.Fill(dt);
      dataGridView1.DataSource = dt;
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

Updated: 2012.07.25
Using parameters:
using (OleDbConnection cnn = new OleDbConnection(
    ConfigurationManager.ConnectionStrings["AccessDB"].ConnectionString))
{
    cnn.Open();
    using (OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem + " Where ID = ?", cnn))
    {
        cmd.Parameters.AddWithValue("memberID", mID);
        OleDbDataReader reader;
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            ....
        }
    }
}
1. Use the question mark (?) to represent the parameter you want to add.
2. When AddWithValue(), the parameter name doesn't matter. The only thing matter is that if the column type you want to filter is an int (as my example here), the value you gave (mID) has to be able to convert to an int. Otherwise, you will get an error.

2008/12/16

Gridview: automatically change focus from one TextBox to the other

In a word, I would like to do something like Excel can do:
1. After inputing data and pressing the "Enter" key, the focus should change to the next TextBox.
2. After focus changed, the content should be selected automatically so that users can repeat step 1.
3. Each "Enter" you press will trigger the postback and do some calculations.
4. If reach the end of the Gridview, do nothing.

Environment:
1.A GridView control + ASP.Net 2.0 application.
2.GridView has an ItemTemplate field, which contains TextBox.
3.GridView is inside an UpdatePanel.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
  //get the parent gridview
  GridViewRow gvr = (GridViewRow)((TextBox)sender).NamingContainer;
  GridView gv = (GridView)gvr.NamingContainer;

  //automatically change focus to the next row's textbox
  if (gvr.RowIndex != gv.Rows.Count - 1)
   ChangeFocus((TextBox)gv.Rows[gvr.RowIndex + 1].FindControl(((TextBox)sender).ID), ScriptManager1);

  gvr = null;
  gv = null;
}

private static void ChangeFocus(TextBox tb, ScriptManager scriptMgr)
{
  tb.Attributes.Add("onfocus", "javascript:this.select();");
  scriptMgr.SetFocus(tb.ClientID);
}

2008/11/07

Dynamically enable/disable ASP.Net AJAX controls

The ASP.Net AJAX Toolkit is a good stuff because it can let you achieve some very cool functions without doing too much hard works. However, how to do it if I want the AJAX control works only in some conditions? For example, I want to have the same function like this one. After many times try and error, I finally figure out the correct procedures. Here are the steps:

Tips: Storing data in the web.config file

You can store any string you want.
<appSettings>
  <add key="SSRS" value="http://localhost/Reports/Pages/Report.aspx" />
  <add key="FTPServer" value="ftp.myftp.com" />
</appSettings>
Here is how to use:
string strSSRS = ConfigurationManager.AppSettings["SSRS"];