Tuesday, January 29, 2013

Updating Dictionary elements while iterating


As we know we can't update dictionary collection element if we are iterating them using foreach loop. For example, we could iterate Dictionary using KeyValuePair in foreach loop but we can't modify them because as per MSDN: "If the iteration variable is a value type, it is effectively a read-only variable that cannot be modified.". So being the iteration variable 'KeyValuePair<TKey, TValue> as a struct type (value type) here, it can't be updated.

But what if we want to iterate the entire dictionary and at the same time also we have a need to modify the Dictionary Elements.Let's see how we can do this:



 
            Dictionary<int, string> ProductCollection = new Dictionary<int, string>();
            
            ProductCollection.Add(1, "AAAAAAAAAAAAAA");
            ProductCollection.Add(4, "BBBBBBBBBBBBBB");
            ProductCollection.Add(7, "CCCCCCCCCCCCCC");
 
            //Iterating entire ProductCollection but we can't update Dictionary element in foreach loop
            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(item.Key + "\t" + item.Value);
            }
 
            //Grab all the Keys and put it in a list
            List<int> ids = ProductCollection.Keys.ToList();
 
            //Iterate all the Dictionary elements through their keys and modify the dictionary elements
            foreach (int idKey in ids)
            {
                ProductCollection[idKey] += "ChangedBy"+idKey.ToString();
            }
 
 
            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(  item.Key + "\t"+ item.Value);
            }
 

Monday, January 21, 2013

How to pass variables from one page to another with Query String

Suppose in one web page, we have a TextBox and a 'Search' Button. On this page, user can enter any name in the TextBox to search and hits the Search button. On hitting search button, another web page opens that displayed the searched result in the grid.

Let's see, how we could do this using query string:

In the Search Button (First webpage) event handler put the code like:


        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Staff.aspx?Name=" + txtBx_Request.Text);
        }


And on the second form page load, get the query string and send the query string to retrieve the data from database. After that we bind the data into a data grid.

        protected void Page_Load(object sender, EventArgs e)
        {
            string reqName = Request.QueryString["Name"];
          
           if (reqName != null && reqName != "")
           {
               Label1.Text = "You queried for the person having name: " + reqName;
               //Getting the data from database
               DataSet resultDataSet = GetDataFromDatabase(storedProcName, reqName);
 
               if (resultDataSet.Tables[0].Rows.Count > 0)
               {
                   GridView1.DataSource = resultDataSet.Tables[0];
                   GridView1.AutoGenerateColumns = true;
                   GridView1.DataBind();
               }
               else
               {
                   Label1.Text += "<br/><br/>Sorry, No data found!";
               }
           }
        }

Get Data using ADO NET DataSet with Stored Procedure

Here is the code:


        DataSet GetDataFromDatabase(string storedProcName, string param1)
        {
            DataSet ds = new DataSet();
 
            //Reading database connection string from Config File
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HKSConnectionString"].ConnectionString;
 
            // Establishing database connection
            using (SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                // Setting SqlCommand with SQLQuery (in this case it's a stored proc name) and SqlConnection
                using (SqlCommand cmd = new System.Data.SqlClient.SqlCommand(storedProcName, sqlConnection))
                {
                    // Letting the SqlCommand know that CommandType is 'StoredProcedure'
                    cmd.CommandType = CommandType.StoredProcedure;
 
                    // Adding parameters
                    cmd.Parameters.AddWithValue("@Name", param1);;
                    
                    // DataAdapter is bind to Command
                    using (SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(cmd))
                    {
                        // Filling the dataset with result data
                        dataAdapter.Fill(ds);
                    }
                }
            }
            return ds;
        }