PageRenderTime 51ms CodeModel.GetById 17ms app.highlight 24ms RepoModel.GetById 2ms app.codeStats 0ms

/Visual Studio 2008/CSASPNETFormViewUpload/Default.aspx.cs

#
C# | 277 lines | 120 code | 47 blank | 110 comment | 3 complexity | 12cc4128fdee0435d5498230cdd65a10 MD5 | raw file
  1/****************************** Module Header ******************************\
  2* Module Name:  Default.aspx.cs
  3* Project:      CSASPNETFormViewUpload
  4* Copyright (c) Microsoft Corporation.
  5* 
  6* This page populates a FromView control with data from a SQL Server 
  7* database and provides UI for data manipulation.
  8* 
  9* This source is subject to the Microsoft Public License.
 10* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
 11* All other rights reserved.
 12* 
 13* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 14* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 15* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 16\***************************************************************************/
 17
 18#region Using directives
 19using System;
 20using System.Collections.Generic;
 21using System.Linq;
 22using System.Web;
 23using System.Web.UI;
 24using System.Web.UI.WebControls;
 25using System.Data.SqlClient;
 26using System.Configuration;
 27using System.Data;
 28#endregion Using directives
 29
 30namespace CSASPNETFormViewUpload
 31{
 32    public partial class Default : System.Web.UI.Page
 33    {
 34        protected void Page_Load(object sender, EventArgs e)
 35        {
 36            // The Page is accessed for the first time.
 37            if (!IsPostBack)
 38            {
 39                // Enable the FormView paging option and 
 40                // specify the PageButton count.
 41                fvPerson.AllowPaging = true;
 42                fvPerson.PagerSettings.PageButtonCount = 15;
 43
 44                // Populate the FormView control.
 45                BindFormView();
 46            }
 47        }
 48
 49        private void BindFormView()
 50        {
 51            // Get the connection string from Web.config. 
 52            // When we use Using statement, 
 53            // we don't need to explicitly dispose the object in the code, 
 54            // the using statement takes care of it.
 55            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"].ToString()))
 56            {
 57                // Create a DataSet object.
 58                DataSet dsPerson = new DataSet();
 59
 60                // Create a SELECT query.
 61                string strSelectCmd = "SELECT PersonID,LastName,FirstName FROM Person";
 62
 63                // Create a SqlDataAdapter object
 64                // SqlDataAdapter represents a set of data commands and a 
 65                // database connection that are used to fill the DataSet and 
 66                // update a SQL Server database. 
 67                SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
 68
 69                // Open the connection
 70                conn.Open();
 71
 72                // Fill the DataTable named "Person" in DataSet with the rows
 73                // returned by the query.
 74                da.Fill(dsPerson, "Person");
 75
 76
 77                // Bind the FormView control.
 78                fvPerson.DataSource = dsPerson;
 79                fvPerson.DataBind();
 80            }
 81        }
 82
 83        // FormView.PageIndexChanging Event
 84        protected void fvPerson_PageIndexChanging(object sender, FormViewPageEventArgs e)
 85        {
 86            // Set the index of the new display page. 
 87            fvPerson.PageIndex = e.NewPageIndex;
 88
 89            // Rebind the FormView control to show data in the new page.
 90            BindFormView();
 91        }
 92
 93        // FormView.ItemInserting Event
 94        protected void fvPerson_ItemInserting(object sender, FormViewInsertEventArgs e)
 95        {
 96            // Get the connection string from Web.config. 
 97            // When we use Using statement, 
 98            // we don't need to explicitly dispose the object in the code, 
 99            // the using statement takes care of it.
100            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"].ToString()))
101            {
102                // Create a command object.
103                SqlCommand cmd = new SqlCommand();
104
105                // Assign the connection to the command.
106                cmd.Connection = conn;
107
108                // Set the command text
109                // SQL statement or the name of the stored procedure. 
110                cmd.CommandText = "INSERT INTO Person ( LastName, FirstName, Picture ) VALUES ( @LastName, @FirstName, @Picture )";
111
112                // Set the command type
113                // CommandType.Text for ordinary SQL statements; 
114                // CommandType.StoredProcedure for stored procedures.
115                cmd.CommandType = CommandType.Text;
116
117                // Get the first name and last name from the 
118                // InsertItemTemplate of the FormView control.
119                string strLastName = ((TextBox)fvPerson.Row.FindControl("tbLastName")).Text;
120                string strFirstName = ((TextBox)fvPerson.Row.FindControl("tbFirstName")).Text;
121
122                // Append the parameters to the SqlCommand and set values.
123                cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = strLastName;
124                cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = strFirstName;
125
126                FileUpload uploadPicture = (FileUpload)fvPerson.FindControl("uploadPicture");
127
128                if (uploadPicture.HasFile)
129                {
130                    // Append the Picture parameter to the SqlCommand.
131                    // If a picture is specified, set the parameter with 
132                    // the value of bytes in the specified picture file. 
133                    cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = uploadPicture.FileBytes;
134                }
135                else
136                {
137                    // Append the Picture parameter to the SqlCommand.
138                    // If no picture is specified, set the parameter's 
139                    // value to NULL.
140                    cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = DBNull.Value;
141                }
142
143                // Open the connection.
144                conn.Open();
145
146                // Execute the command.
147                cmd.ExecuteNonQuery();
148            }
149
150            // Switch FormView control to the ReadOnly display mode. 
151            fvPerson.ChangeMode(FormViewMode.ReadOnly);
152
153            // Rebind the FormView control to show data after inserting.
154            BindFormView();
155        }
156
157        // FormView.ItemUpdating Event
158        protected void fvPerson_ItemUpdating(object sender, FormViewUpdateEventArgs e)
159        {
160            // Get the connection string from Web.config. 
161            // When we use Using statement, 
162            // we don't need to explicitly dispose the object in the code, 
163            // the using statement takes care of it.
164            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"].ToString()))
165            {
166                // Create a command object.
167                SqlCommand cmd = new SqlCommand();
168
169                // Assign the connection to the command.
170                cmd.Connection = conn;
171
172                // Set the command text
173                // SQL statement or the name of the stored procedure. 
174                cmd.CommandText = "UPDATE Person SET LastName = @LastName, FirstName = @FirstName, Picture = ISNULL(@Picture,Picture) WHERE PersonID = @PersonID";
175
176                // Set the command type
177                // CommandType.Text for ordinary SQL statements; 
178                // CommandType.StoredProcedure for stored procedures.
179                cmd.CommandType = CommandType.Text;
180
181                // Get the person ID, first name and last name from the 
182                // EditItemTemplate of the FormView control.
183                string strPersonID = ((Label)fvPerson.Row.FindControl("lblPersonID")).Text;
184                string strLastName = ((TextBox)fvPerson.Row.FindControl("tbLastName")).Text;
185                string strFirstName = ((TextBox)fvPerson.Row.FindControl("tbFirstName")).Text;
186
187                // Append the parameters to the SqlCommand and set values.
188                cmd.Parameters.Add("@PersonID", SqlDbType.Int).Value = strPersonID;
189                cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = strLastName;
190                cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = strFirstName;
191
192                // Find the FileUpload control in the EditItemTemplate of 
193                // the FormView control.
194                FileUpload uploadPicture = (FileUpload)fvPerson.FindControl("uploadPicture");
195
196                if (uploadPicture.HasFile)
197                {
198                    // Append the Picture parameter to the SqlCommand.
199                    // If a picture is specified, set the parameter with 
200                    // the value of bytes in the specified picture file. 
201                    cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = uploadPicture.FileBytes;
202                }
203                else
204                {
205                    // Append the Picture parameter to the SqlCommand.
206                    // If no picture is specified, set the parameter's 
207                    // value to NULL.
208                    cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = DBNull.Value;
209                }
210
211                // Open the connection.
212                conn.Open();
213
214                // Execute the command.
215                cmd.ExecuteNonQuery();
216            }
217
218            // Switch FormView control to the ReadOnly display mode. 
219            fvPerson.ChangeMode(FormViewMode.ReadOnly);
220
221            // Rebind the FormView control to show data after updating.
222            BindFormView();
223        }
224
225        // FormView.ItemDeleting Event
226        protected void fvPerson_ItemDeleting(object sender, FormViewDeleteEventArgs e)
227        {
228            // Get the connection string from Web.config. 
229            // When we use Using statement, 
230            // we don't need to explicitly dispose the object in the code, 
231            // the using statement takes care of it.
232            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer2005DBConnectionString"].ToString()))
233            {
234                // Create a command object.
235                SqlCommand cmd = new SqlCommand();
236
237                // Assign the connection to the command.
238                cmd.Connection = conn;
239
240                // Set the command text
241                // SQL statement or the name of the stored procedure. 
242                cmd.CommandText = "DELETE FROM Person WHERE PersonID = @PersonID";
243
244                // Set the command type
245                // CommandType.Text for ordinary SQL statements; 
246                // CommandType.StoredProcedure for stored procedures.
247                cmd.CommandType = CommandType.Text;
248
249                // Get the PersonID from the ItemTemplate of the FormView 
250                // control.
251                string strPersonID = ((Label)fvPerson.Row.FindControl("lblPersonID")).Text;
252
253                // Append the parameter to the SqlCommand and set value.
254                cmd.Parameters.Add("@PersonID", SqlDbType.Int).Value = strPersonID;
255
256                // Open the connection.
257                conn.Open();
258
259                // Execute the command.
260                cmd.ExecuteNonQuery();
261            }
262
263            // Rebind the FormView control to show data after deleting.
264            BindFormView();
265        }
266
267        // FormView.ModeChanging Event
268        protected void fvPerson_ModeChanging(object sender, FormViewModeEventArgs e)
269        {
270            // Switch FormView control to the new mode
271            fvPerson.ChangeMode(e.NewMode);
272
273            // Rebind the FormView control to show data in new mode.
274            BindFormView();
275        }   
276    }
277}