How to Select a record using Listbox and edit/update it’s fields using textboxes

<TABLE class=’cdb-AltRow2′ id=’Table1′ style=’Z-INDEX: 101; LEFT: 189px; POSITION: absolute; TOP: 20px’ cellSpacing=’1′ cellPadding=’1′ width=’300′ border=’0′> <TR> <TD>ProductID</TD> <TD><asp:textbox id=’txtProductId’ runat=’server’ Enabled=’False’></asp:textbox></TD> </TR> <TR> <TD>Quantity per unit</TD> <TD><asp:textbox id=’txtQuantity’ runat=’server’></asp:textbox></TD> </TR> <TR> <TD>UnitPrice</TD> <TD><asp:textbox id=’txtUnitPrice’ runat=’server’></asp:textbox></TD> </TR> <TR> <TD></TD> <TD><asp:button id=’btnUpdate’ runat=’server’ Text=’Update’></asp:button></TD> </TR> <TR> <TD></TD> <TD><asp:label id=’lblError’ runat=’server’ Visible=’False’></asp:label></TD> </TR> </TABLE> <asp:listbox id=’ListBox1′ style=’Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 12px’ runat=’server’ AutoPostBack=’True’></asp:listbox> VB.NET Dim productid As String Dim strSQL As String Dim strConn As String Dim dr, dr1 As SqlDataReader Dim mycn As SqlConnection Dim mycmd As SqlCommand Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load strConn = ‘server=localhost;uid=sa;database=northwind;pwd=;’ lblError.Visible = False ’ Put user code to initialize the page here If Not Page.IsPostBack Then mycn = New SqlConnection(strConn) strSQL = ‘Select * from Products’ mycmd = New SqlCommand(strSQL, mycn) mycn.Open() dr = mycmd.ExecuteReader(CommandBehavior.CloseConnection) ListBox1.DataSource = dr ListBox1.DataTextField = ‘ProductID’ ListBox1.DataValueField = ‘ProductID’ ListBox1.DataBind() End If End Sub ’Page_Load Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click Try lblError.Visible = False Dim updateCmd As String = ‘UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ,’ + ‘UnitPrice = @UnitPrice where ProductId=@ProductId’ Dim cn As New SqlConnection(strConn) Dim myCommand As New SqlCommand(updateCmd, cn) myCommand.Parameters.Add(New SqlParameter(‘@QuantityPerUnit’, txtQuantity.Text)) myCommand.Parameters.Add(New SqlParameter(‘@UnitPrice’, Convert.ToDouble(txtUnitPrice.Text))) myCommand.Parameters.Add(New SqlParameter(‘@ProductId’, Convert.ToInt16(txtProductId.Text))) cn.Open() myCommand.ExecuteNonQuery() lblError.Visible = True lblError.Text = ‘Record Updated successfully’ Catch ex As Exception lblError.Visible = True lblError.Text = ex.Message End Try End Sub ’btnUpdate_Click Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged productid = ListBox1.SelectedItem.Value txtProductId.Text = productid.ToString() strSQL = ‘Select * from Products where productid =’ + productid mycn = New SqlConnection(strConn) mycmd = New SqlCommand(strSQL, mycn) mycn.Open() dr1 = mycmd.ExecuteReader(CommandBehavior.CloseConnection) If dr1.Read() Then txtProductId.Text = dr1(‘ProductId’).ToString() txtQuantity.Text = dr1(‘QuantityPerUnit’).ToString() txtUnitPrice.Text = dr1(‘UnitPrice’).ToString() Else Response.Write(‘No data found’) End If End Sub ’ListBox1_SelectedIndexChanged C# string productid; string strSQL; string strConn; SqlDataReader dr,dr1; SqlConnection mycn; SqlCommand mycmd; private void Page_Load(object sender, System.EventArgs e) { strConn =’server=localhost;uid=sa;database=northwind;pwd=;’; lblError.Visible =false; // Put user code to initialize the page here if (!Page.IsPostBack ) { mycn = new SqlConnection(strConn); strSQL =’Select * from Products’; mycmd = new SqlCommand (strSQL, mycn); mycn.Open (); dr=mycmd.ExecuteReader(CommandBehavior.CloseConnection ); ListBox1.DataSource = dr; ListBox1.DataTextField =’ProductID’; ListBox1.DataValueField =’ProductID’; ListBox1.DataBind (); } } private void btnUpdate_Click(object sender, System.EventArgs e) { try { lblError.Visible =false; string updateCmd = ‘UPDATE Products SET QuantityPerUnit = @QuantityPerUnit ,’ + ‘UnitPrice = @UnitPrice where ProductId=@ProductId’; SqlConnection cn = new SqlConnection (strConn); SqlCommand myCommand = new SqlCommand(updateCmd, cn); myCommand.Parameters.Add(new SqlParameter(‘@QuantityPerUnit’, txtQuantity.Text )); myCommand.Parameters.Add(new SqlParameter(‘@UnitPrice’, Convert.ToDouble( txtUnitPrice.Text ))); myCommand.Parameters.Add(new SqlParameter(‘@ProductId’, Convert.ToInt16 ( txtProductId.Text))); cn.Open (); myCommand.ExecuteNonQuery (); lblError.Visible =true; lblError.Text =’Record Updated successfully’; } catch(Exception ex) { lblError.Visible =true; lblError.Text =(ex.Message ); } } private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) { productid = ListBox1.SelectedItem.Value ; txtProductId.Text =productid.ToString (); strSQL = ‘Select * from Products where productid =’ + productid ; mycn = new SqlConnection(strConn); mycmd = new SqlCommand (strSQL, mycn); mycn.Open (); dr1=mycmd.ExecuteReader(CommandBehavior.CloseConnection ); if(dr1.Read() ) { txtProductId.Text = dr1[‘ProductId’].ToString (); txtQuantity.Text = dr1[‘QuantityPerUnit’].ToString (); txtUnitPrice.Text = dr1[‘UnitPrice’].ToString (); } else { Response.Write (‘No data found’); } }

How to save the Output of ASP.NET to HTML

Use the namespaces System.Net which have classes WebRequest and WebResponse. WebRequest is the abstract base class for the .NET Framework’s request/response model for accessing data from the internet and WebResponse is the abstract base class from which protocol specific response classes are derived. System.IO which have classes StreamReader and StreamWriter. StreamReader designed for character input in a particular encoding. StreamWriter designed for character output in a particular encoding. VB.NET Dim mywebReq As WebRequest Dim mywebResp As WebResponse Dim sr As StreamReader Dim strHTML As String Dim sw As StreamWriter Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ’Give the Appropriate URL for .aspx page. in this case its ‘http://www.syncfusion.com/faq/aspnet’ mywebReq = WebRequest.Create(‘http://www.syncfusion.com/faq/aspnet’) mywebResp = mywebReq.GetResponse() sr = New StreamReader(mywebResp.GetResponseStream) strHTML = sr.ReadToEnd sw = File.CreateText(Server.MapPath(‘temp.html’)) sw.WriteLine(strHTML) sw.Close() Response.WriteFile(Server.MapPath(‘temp.html’)) End Sub C# WebRequest mywebReq ; WebResponse mywebResp ; StreamReader sr ; string strHTML ; StreamWriter sw; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here mywebReq = WebRequest.Create(‘http://www.syncfusion.com/faq/aspnet’); mywebResp = mywebReq.GetResponse(); sr = new StreamReader(mywebResp.GetResponseStream()); strHTML = sr.ReadToEnd(); sw = File.CreateText(Server.MapPath(‘temp.html’)); sw.WriteLine(strHTML); sw.Close(); Response.WriteFile(Server.MapPath(‘temp.html’)); } Note:For creating the file (in above case ‘temp.html’) give appropriate rights (modify and write) to the ASPNET user. To specify the Encoding specify the second parameter of the StreamReader accordingly VB.NET sr = New StreamReader(mywebResp.GetResponseStream, System.Text.Encoding.ASCII) C# sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);

How can you do ClientSide Validation?

Client-side validation is enabled by default. If the client is capable, uplevel validation will be performed automatically. To disable client-side validation, set the page’s ClientTarget property to ‘Downlevel’ (‘Uplevel’ forces client-side validation). Alternatively, you can set an individual validator control’s EnableClientScript property to ‘false’ to disable client-side validation for that specific control. <%@ Page ClientTarget=UpLevel %> <html> <head> <script language=”C#” runat=server> void Page_Load() { if (!IsPostBack) { // Validate initially to force *s to appear before the first round-trip Validate(); } } void ValidateBtn_Click(Object Sender, EventArgs E) { if (Page.IsValid == true) { lblOutput.Text = “Page is Valid!”; } else { lblOutput.Text = “Some of the required fields are empty”; } } </script> </head> <body> <h3><font face=”Verdana”>Client-Side RequiredFieldValidator Sample</font></h3> <form runat=”server”> <table bgcolor=”#eeeeee” cellpadding=10> <tr valign=”top”> <td colspan=3> <asp:Label ID=”lblOutput” Name=”lblOutput” Text=”Fill in the required fields below” ForeColor=”red” Font-Names=”Verdana” Font-Size=”10″ runat=server /><br> </td> </tr> <tr> <td colspan=3> <font face=Verdana size=2><b>Credit Card Information</b></font> </td> </tr> <tr> <td align=right> <font face=Verdana size=2>Card Type:</font> </td> <td> <ASP:RadioButtonList id=RadioButtonList1 RepeatLayout=”Flow” onclick=”ClientOnChange();” runat=server> <asp:ListItem>MasterCard</asp:ListItem> <asp:ListItem>Visa</asp:ListItem> </ASP:RadioButtonList> </td> <td align=middle rowspan=1> <asp:RequiredFieldValidator id=”RequiredFieldValidator1″ runat=”server” ControlToValidate=”RadioButtonList1″ ErrorMessage=”*” Display=”Static” InitialValue=”” Width=”100%”> </asp:RequiredFieldValidator> </td> </tr> <tr> <td align=right> <font face=Verdana size=2>Card Number:</font> </td> <td> <ASP:TextBox id=TextBox1 onchange=”ClientOnChange();” runat=server /> </td> <td> <asp:RequiredFieldValidator id=”RequiredFieldValidator2″ runat=”server” ControlToValidate=”TextBox1″ ErrorMessage=”*” Display=”Static” Width=”100%”> </asp:RequiredFieldValidator> </td> </tr> <tr> <td align=right> <font face=Verdana size=2>Expiration Date:</font> </td> <td> <ASP:DropDownList id=DropDownList1 onchange=”ClientOnChange();” runat=server> <asp:ListItem></asp:ListItem> <asp:ListItem >06/00</asp:ListItem> <asp:ListItem >07/00</asp:ListItem> <asp:ListItem >08/00</asp:ListItem> <asp:ListItem >09/00</asp:ListItem> <asp:ListItem >10/00</asp:ListItem> <asp:ListItem >11/00</asp:ListItem> <asp:ListItem >01/01</asp:ListItem> <asp:ListItem >02/01</asp:ListItem> <asp:ListItem >03/01</asp:ListItem> <asp:ListItem <04/01</asp:ListItem> <asp:ListItem <05/01</asp:ListItem> <asp:ListItem <06/01</asp:ListItem> <asp:ListItem <07/01</asp:ListItem> <asp:ListItem <08/01</asp:ListItem> <asp:ListItem <09/01</asp:ListItem> <asp:ListItem <10/01</asp:ListItem> <asp:ListItem <11/01</asp:ListItem> <asp:ListItem <12/01</asp:ListItem> </ASP:DropDownList> </td> <td> <asp:RequiredFieldValidator id=”RequiredFieldValidator3″ runat=”server” ControlToValidate=”DropDownList1″ ErrorMessage=”*” Display=”Static” InitialValue=”” Width=”100%”> </asp:RequiredFieldValidator> </td> <td> </tr> <tr> <td> </td> <td> <ASP:Button id=Button1 text=”Validate” OnClick=”ValidateBtn_Click” runat=”server” /> </td> <td> </td> </tr> </table> </form> <script language=javascript> <!– function ClientOnChange() { if (typeof(Page_Validators) == “undefined”) return; document.all[“lblOutput”].innerText = Page_IsValid ? “Page is Valid!” : “Some of the required fields are empty”; } // –> </script> </body> </html>