5. User controls 6.1 How can I include an Asp.NET page in many other Asp.Net pages so that I don't need to rewrite the code? One of the approaches is to write and use a UserControl. You can define the user interface, handle events and expose properties in a UserControl, and then mark a reference and reuse these Controls in any page of your Web application. Here is some Sample code 6.2 Is there anything similar to web templates in ASP that I can use in ASP.Net? In ASP.NET, you would typically use a User Control to create reusable controls. 6.3 Are there any settings on the application level to make certain elements appear on every page without having to manually insert code or insert UserControls? You can use HttpHandlers and/or HttpModules to insert information on all pages transparently. Check out Bipin Joshi's article Extending ASP.NET with HttpHandlers and HttpModules 6.4 How to pass a parameter to a user control? Create a User Control Below Code goes in User Control <asp:ImageButton id="ImageButton1" runat="server"></asp:ImageButton> Create a property called source VB.NET Public Property source() As String Get Return ImageButton1.ImageUrl End Get Set(ByVal Value As String) ImageButton1.ImageUrl = Value End Set End Property 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
5. User controls
6.1 How can I include an Asp.NET page in many other Asp.Net pages so that I don't need to rewrite the code?
One of the approaches is to write and use a UserControl. You can define the user interface, handle events and
expose properties in a UserControl, and then mark a reference and reuse these Controls in any page of your Web
application.
Here is some Sample code
6.2 Is there anything similar to web templates in ASP that I can use in ASP.Net?
In ASP.NET, you would typically use a User Control to create reusable controls.
6.3 Are there any settings on the application level to make certain elements appear on every page without having to manually insert code or insert UserControls?
You can use HttpHandlers and/or HttpModules to insert information on all pages transparently. Check out Bipin
Joshi's article Extending ASP.NET with HttpHandlers and HttpModules
Public Property source() As String Get Return ImageButton1.ImageUrl End Get Set(ByVal Value As String) ImageButton1.ImageUrl = Value End Set End Property
Dim uc1 As UserControl = CType(LoadControl("uc1.ascx"), UserControl) Controls.Add(uc1) Dim uc2 As Control = uc1.LoadControl("uc2.ascx") Dim p1 As Control = uc1.FindControl("p1") p1.Controls.Add(uc2)
C#
UserControl uc1 = (UserControl)LoadControl("uc1.ascx"); Controls.Add(uc1); Control uc2 = uc1.LoadControl("uc2.ascx"); Control p1 = uc1.FindControl("p1"); p1.Controls.Add(uc2);
6.6 I have a function inside of the .ascx file. How can I call it from the web application page(the .aspx file)?
Dim UC As UserControl Dim imgUC As System.Web.UI.WebControls.Image UC = Page.FindControl("UCImage1") imgUC = UC.FindControl("Image1") imgUC.ImageUrl = "b2346.jpg"
Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would automatically
use NTLM to authenticate you as SYNCFUSION\user1 (for example).
Forms based authentication, then you would use an html based forms page to enter username/password --
which would then check a database and authenticate you against the username/password in the database.
Authorization is the process of determining whether an authenticated user has access to run a particular page within an ASP.NET web application. Specifically, as an application author decide to grant or deny the authenticated user "SYNCFUSION\user1" access to the admin.aspx page. This could be done either by explictly granting/denying rights based on the username -- or use role based mappings to map authenticated users into roles (for example: an administrator might map "SYNCFUSION\user1" into the "Power Users" role) and then grant/deny access based on role names (allowing a degree of abstraction to separate out your authorization policy).
9.2 How to implement authentication via web.config?
You are encouraged to read the script to see more of what is going on. However, it is not recommended that you modify these scripts, because their function is very closely tied to a particular version of the run time. If the run time is updated, the scripts may need a corresponding update, and you will have to either lose your changes or face problems with the scripts not working. If you must change the scripts for a particular project, take a copy of the files and point your project to them by overriding the location of the files with a private web.config file.It is perfectly fine to change this location to be a relative or absolute reference.
12.3 How to read data from the XML file using FileStream and display it in a DataGrid?
Use namespace System.IO
VB.NET
dim ds as new DataSet() dim fs as FileStream = new FileStream (Server.MapPath ("products.xml"),FileMode.Open , FileAccess.Read ) ds.ReadXml (fs) DataGrid1.DataSource = ds DataGrid1.DataBind ()
RadioButton control is designed to allow users to choose atleast one option from a list of available options.
Checkbox is designed to allow users to choose from zero to all options.
21.3 How can I enforce that only one radiobutton gets selected among a list of Radiobutton controls?
Set same Groupname for the radiobutton controls
10. Controls22.1 How to close the browser window on button control click?
Method 1. This will cause a postback on button click in response to which we will send some script to close the
window.
VB.NET Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Response.Write("<script>window.close();</script>") End Sub
Method 2. This is preferrable since there is no postback involved.
Use the Attribute collections i.e use Attributes of button control to add client side JavaScript code VB.NET Button1.Attributes.Add("OnClick", "window.close();")
'Textbox Dim txtBox As TextBox = New TextBox txtBox.ControlStyle.CssClass = "textbox" txtBox.ID = "txtbox" + i.ToString()
'RequiredFieldValidator Dim rqdVal As RequiredFieldValidator = New RequiredFieldValidator rqdVal.ID = "rqdVal" + i.ToString() rqdVal.ControlToValidate = "txtbox" + i.ToString() rqdVal.ErrorMessage = "Please enter a value" rqdVal.Display = ValidatorDisplay.Dynamic
'RangeValidator Dim rngVal As RangeValidator = New RangeValidator rngVal.ID = "rngVal" + i.ToString() rngVal.MinimumValue = "1" rngVal.MaximumValue = "100" rngVal.ControlToValidate = "txtbox" + i.ToString() rngVal.Type = ValidationDataType.Double rngVal.ErrorMessage = " Value should be between 1 and 100"
'Add Controls on the page Page.Controls(1).Controls.Add(txtBox) Page.Controls(1).Controls.Add(rqdVal) Page.Controls(1).Controls.Add(rngVal)
//RequiredFieldValidator RequiredFieldValidator rqdVal = new RequiredFieldValidator(); rqdVal.ID = "rqdVal" + i.ToString(); rqdVal.ControlToValidate = "txtbox" + i.ToString(); rqdVal.ErrorMessage = "Please enter a value"; rqdVal.Display =ValidatorDisplay.Dynamic;
//RangeValidator RangeValidator rngVal = new RangeValidator(); rngVal.ID = "rngVal" + i.ToString(); rngVal.MinimumValue = "1"; rngVal.MaximumValue = "100"; rngVal.ControlToValidate = "txtbox" + i.ToString(); rngVal.Type = ValidationDataType.Double; rngVal.ErrorMessage = " Value should be between 1 and 100";
//Add Controls on the page Page.Controls[1].Controls.Add (txtBox); Page.Controls[1].Controls.Add (rqdVal); Page.Controls[1].Controls.Add (rngVal);
22.5 How to change the image button size during runtime?
VB.NET
Dim x As New Unit("80px") Dim y As New Unit("20px") Dim imagestate as string= "stand" If imagestate = "stand" then imagebutton1.height = x else imagebutton1.height = y end if
C#
Unit x = new Unit ("80px"); Unit y = new Unit("20px"); string imagestate="stand"; if( imagestate != "stand") { ImageButton1.Height = x; } else { ImageButton1.Height = y; }
For more details Setting Web Server Control Properties Programmatically
22.6 How can I to divide the .aspx page to different parts with different functionality in a neat and organized manner. Is there any control that can do that?
You can use Panel controls, which render as HTML div elements. You can then show or hide the panels by
enabling/disabling them. In addition, you can specify different formatting options for different Panels/divs using
manual formatting or CSS styles.
22.7 How to maintain Scroll Position in any Page Element?
Check out Jim Ross's article Maintain Scroll Position in any Page Element
The article describes, when using a scrollable Datagrid--one inside an overflow-auto DIV control--how to maintain the
user's scroll position inside the DIV across postbacks. It does this using IE behaviors, HTC files.
22.8 DataBinder.Eval imposes performance penalty on code as it uses late bound reflection. How can I replace this calls with explicit calls?
Protected Function createStyleForControl(ByVal _forecolor As Color, ByVal _backcolor As Color, ByVal _fontbold As Boolean) As Style Dim s As Style = New Style s.ForeColor = _forecolor s.BackColor = _backcolor s.Font.Bold = _fontbold Return s End Function
In Page_Load
Dim textboxStyle As Style = createStyleForControl(Color.Pink, Color.Yellow, False) Dim buttonStyle As Style = createStyleForControl(Color.Blue, Color.Teal, True) Dim checkboxStyle As Style = createStyleForControl(Color.AliceBlue, Color.PowderBlue, False)
Note: Based on the criteria you can hide and show panels
22.14 Why do I get error message "The control '_ctl1' of type 'TextBox' must be inside a form label with runat=server" while trying to place a control inside a form dynamically?
You are probably adding the textbox into the Page directly instead of adding it to the Page's form. Try doing this:
VB.NET
Me.Page.Controls(1).Controls.Add(txtboxctrl)
C#
this.Page.Controls[1].Controls.Add(txtboxctrl);
22.15 How to implement mouseover effects in a <asp:image> web server control?
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here If Not Page.IsPostBack Then Button1.Style.Add("LEFT", "1px") End If End Sub 'Page_Load
Private Sub RadioButtonList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButtonList1.SelectedIndexChanged Button1.Style.Add("LEFT", RadioButtonList1.SelectedItem.Value.ToString()) End Sub 'RadioButtonList1_SelectedIndexChanged
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { Button1.Style.Add("LEFT", "1px"); } }
... Dim dtMinDate As DateTime Dim dtMaxDate As DateTime dtMinDate = Convert.ToDateTime("04/25/04") dtMaxDate = Convert.ToDateTime("10/17/04") RangeValidator1.MinimumValue = dtMinDate RangeValidator1.MaximumValue = dtMaxDate TextBox1.Text = dtMaxDate.ToShortDateString RangeValidator1.ErrorMessage = "Not in Range of " & dtMinDate.ToShortDateString() & " to " & dtMaxDate.ToShortDateString()
C#
DateTime dtMinDate ; DateTime dtMaxDate ; dtMinDate = Convert.ToDateTime("04/25/04"); dtMaxDate = Convert.ToDateTime("10/17/04"); RangeValidator1.MinimumValue = dtMinDate.ToShortDateString () ; RangeValidator1.MaximumValue = dtMaxDate.ToShortDateString () ; TextBox1.Text = dtMaxDate.ToShortDateString(); RangeValidator1.ErrorMessage = "Not in Range of " + dtMinDate.ToShortDateString() + " to " + dtMaxDate.ToShortDateString();
22.18 How to specifiy the hspace and vspace in a <asp:Image>?
Protected Function GetControls() As ArrayList Dim arrList As New ArrayList() Dim t As Type For Each t In GetType(Page).Assembly.GetTypes() If t.Namespace = "System.Web.UI.WebControls" And GetType(Control).IsAssignableFrom(t) Then arrList.Add(t) End If Next Return arrList End Function 'GetControls
'In Page_Load DataBind()
C#
protected ArrayList GetControls() { ArrayList arrList = new ArrayList(); foreach (Type t in typeof(Page ).Assembly.GetTypes()) { if (t.Namespace == "System.Web.UI.WebControls" && typeof(Control).IsAssignableFrom(t)) arrList.Add(t); }
Dim mycn As SqlConnection Dim myda As SqlDataAdapter Dim ds As DataSet mycn = New SqlConnection("server = localhost;uid=sa;password=;database=northwind") myda = New SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn) ds = New DataSet myda.Fill(ds, "Employees")
Dim dc As DataColumn Dim dr As DataRow For Each dr In ds.Tables(0).Rows
Dim trow As New TableRow For Each dc In ds.Tables(0).Columns Dim tcell As New TableCell tcell.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString)) trow.Cells.Add(tcell) Next Table1.Rows.Add(trow) Next
C#
SqlConnection mycn ; SqlDataAdapter myda ; DataSet ds ; mycn = new SqlConnection("server = localhost;uid=sa;password=;database=northwind"); myda = new SqlDataAdapter("Select Employeeid, FirstName , LastName from employees", mycn); ds = new DataSet(); myda.Fill(ds, "Employees");
TableRow trow ; TableCell tcell; foreach (DataRow dr in ds.Tables[0].Rows) { trow = new TableRow (); foreach( DataColumn dc in ds.Tables[0].Columns) { tcell= new TableCell (); tcell.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString())); trow.Cells.Add(tcell); } Table1.Rows.Add(trow); }
23.2 How to limit table cell size with long strings?
Set style property for the table cell as
style="WORD-BREAK:break-all"
23.3 How to use a Table control to display data vertically?
'Populate the DataSet ds Dim dr As DataRow For Each dc In ds.Tables(0).Columns Dim trow As New TableRow() Dim tcellcolname As New TableCell() 'To Display the Column Names
For Each dr In ds.Tables(0).Rows tcellcolname.Text = dc.ColumnName trow.BackColor = System.Drawing.Color.Beige tcellcolname.BackColor = System.Drawing.Color.AliceBlue 'Populate the TableCell with the Column Name tcellcolname.Controls.Add(New LiteralControl(dc.ColumnName.ToString)) Next trow.Cells.Add(tcellcolname) 'To Display the Column Data For Each dr In ds.Tables(0).Rows Dim tcellcoldata As New TableCell() 'Populate the TableCell with the Column Data tcellcoldata.Controls.Add(New LiteralControl(dr(dc.ColumnName).ToString)) trow.Cells.Add(tcellcoldata) Next Table1.Rows.Add(trow) Next
C#
//Populate the DataSet ds foreach(DataColumn dc in ds.Tables[0].Columns ) { TableRow trow = new TableRow(); TableCell tcellcolname = new TableCell() ; foreach(DataRow dr in ds.Tables[0].Rows ) { tcellcolname.Text = dc.ColumnName ; trow.BackColor = System.Drawing.Color.Beige ; tcellcolname.BackColor = System.Drawing.Color.AliceBlue ; //Populate the TableCell with the Column Name tcellcolname.Controls.Add(new LiteralControl(dc.ColumnName.ToString())) ; } trow.Cells.Add(tcellcolname) ; //To Display the Column Data foreach(DataRow dr in ds.Tables[0].Rows ) { TableCell tcellcoldata =new TableCell() ; //Populate the TableCell with the Column Data tcellcoldata.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString())) ; trow.Cells.Add(tcellcoldata); } Table1.Rows.Add(trow) ; }
23.4 Are there any IE specific performance imporvement possible with Table Layout?
In IE5 and later, significantly faster Table Rendering is now possible. Here is some information in MSDN : Enhancing
Table Presentation.
Among other things, you can specific col specific widths using the colgroup tag or col tag and also set the visibility
25.4 Why am I getting an 'AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection' Error?
You are probably trying to implement paging in a DataGrid while binding the DataGrid with a DataReader. To fix this,
instead of using a DataReader use a DataSet
25.5 How do I use a "helper function" to change the column value as Boolean in database to be displayed as Yes/No in Datagrid?
protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) If (e.Item.ItemType = ListItemType.Item Or _ e.Item.ItemType = ListItemType.AlternatingItem) Then If e.Item.DataItem(6) > 15 Then e.Item.Cells(6).ForeColor = System.Drawing.Color.Green Else e.Item.Cells(6).ForeColor = System.Drawing.Color.Red End If End If End Sub
Dim cn As SqlConnection Dim cmd As SqlCommand Dim rdr As SqlDataReader
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here Try cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind") cmd = New SqlCommand("select * from employees ", cn) cn.Open() rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection) DataGrid1.DataSource = rdr DataGrid1.DataBind() Catch ex As Exception Response.Write(ex.Message.ToString()) Finally rdr.Close() cn.Close() End Try End Sub 'Page_Load
C#
SqlConnection cn ; SqlCommand cmd ; SqlDataReader rdr ; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here try { cn = new SqlConnection("server=localhost;uid=sa;pwd=;database=northwind"); cmd = new SqlCommand( "select * from employees ", cn); cn.Open(); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection ); DataGrid1.DataSource = rdr; DataGrid1.DataBind(); } catch (Exception ex) { Response.Write (ex.Message.ToString ()); } finally { rdr.Close(); cn.Close(); } }
Dim cn As SqlConnection Dim da As SqlDataAdapter Dim ds As DataSet Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind") da = New SqlDataAdapter("Select * from products", cn) ds = New DataSet da.Fill(ds, "Products") DataGrid1.DataSource = ds.Tables(0) 'DataGrid1.DataSource = ds 'DataGrid1.DataSource = ds.Tables("Product") DataGrid1.DataBind() End Sub
C#
SqlConnection cn; SqlDataAdapter da; DataSet ds; private void Page_Load(object sender, System.EventArgs e) { cn= new SqlConnection ("Server=localhost;uid=sa;pwd=;database=northwind"); da= new SqlDataAdapter ("SELECT * FROM Products ", cn); ds= new DataSet (); da.Fill (ds, "Product"); DataGrid1.DataSource =ds.Tables[0]; //DataGrid1.DataSource= ds; //DataGrid1.DataSource= ds.Tables["Products"]; DataGrid1.DataBind (); }
25.13 Why do I get "Could not lock file" and "cannot open file" exceptions when bound to a mdb file?
You could get this error for the following reasons:
1. When you create a project afresh, add a new OleDbDataAdapter to the form and link to the mdb file, the
connection object created in the process will keep an open connection to the mdb file which is what will
cause the above "Could not lock file" exception during runtime. To workaround this, go to "Server Explorer"
in your IDE, right click on the corresponding "Connection entry" and select Close Connection. This should fix
2. The "cannot open file" exception could then occur if you have not provided enough permissions on the mdb
file to allow the .net runtime to lock it. To ensure enough permissions, open it's properties, select the
Security tab and add a "Everyone" account granting "Full Control" to it. This should let the .net runtime lock
the file.
25.14 I am binding the DataGrid to a datasource at runtime. After binding I want to populate a listbox with the column headers from the datagrid. How can I reference the column headertext for each column in the datagrid and then add them to my listbox?
In the ItemDataBound Event write following code VB.NET
Dim i As Integer = 0 If e.Item.ItemType = ListItemType.Header Then For i = 0 To e.Item.Cells.Count -1 Me.ListBox1.Items.Add(e.Item.Cells(i).Text) Next End If
C#
if (e.Item.ItemType== ListItemType.Header) { for(int i = 0; i <= e.Item.Cells.Count-1 ; i++) { this.ListBox1.Items.Add(new ListItem(e.Item.Cells[i].Text)); } }
25.15 When I try to do an Update from my Datagrid, I keep getting the old/original values. Why?
This could happen if you are calling .DataBind everytime the Page is loaded
To avoid this call Databind only for the first request and not for subsequent postbacks.
VB.NET
if not Page.IsPostBack then 'Your databinding code end if
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then BindDataGrid("ProductId") End If End Sub
Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) BindDataGrid(e.SortExpression.ToString()) End Sub
Sub BindDataGrid(ByVal sortfield As String) 'Fill the Dataset '..... Dim dv As DataView = ds.Tables(0).DefaultView dv.Sort = sortfield DataGrid1.DataSource = dv DataGrid1.DataBind() End Sub
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(! Page.IsPostBack ) { BindDataGrid("ProductId"); } }
protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e ) { BindDataGrid(e.SortExpression.ToString()); }
void BindDataGrid(string sortfield) { //Fill the Dataset //..... DataView dv = ds.Tables[0].DefaultView; dv.Sort = sortfield; DataGrid1.DataSource = dv; DataGrid1.DataBind(); }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then Binddata() End If End Sub
Protected Sub PageData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) DataGrid1.CurrentPageIndex = e.NewPageIndex Binddata() End Sub
Sub Binddata() 'Populate the DataGrid using DataSet End Sub
// Put user code to initialize the page here if(! Page.IsPostBack ) { Binddata(); } } protected void PageData(Object source , System.Web.UI.WebControls.DataGridPageChangedEventArgs e ) { DataGrid1.CurrentPageIndex = e.NewPageIndex; Binddata(); }
void Binddata() { //Populate the DataGrid using DataSet }
25.21 How to display an image field in each row of DataGrid?
If the image field is a string representing a image file name, then:
Dim sqlStmt As String Dim conString As String Dim cn As SqlConnection = Nothing Dim da As SqlDataAdapter = Nothing Dim ds As DataSet
Private Sub Page_Load(sender As Object, e As System.EventArgs) conString = "server=localhost;database=Northwind;uid=sa;pwd=;" cn = New SqlConnection(conString) If Not Page.IsPostBack Then BindData() End If End Sub 'Page_Load
Sub BindData() sqlStmt = "select * from emp " ds = New DataSet() da = New SqlDataAdapter(sqlStmt, cn) da.Fill(ds, "t1") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub 'BindData
Protected Sub ItemCrt(sender As Object, e As DataGridItemEventArgs) Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem Dim btn As Button = CType(e.Item.Cells(0).Controls(0), Button) btn.Attributes.Add("onclick", "return confirm('are you sure you want to delete this')") Exit End Select End Sub 'ItemCrt
Protected Sub DelCmd(sender As [Object], e As DataGridCommandEventArgs) DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString()) BindData() End Sub 'DelCmd
Private Sub DeleteRow(empid As String) Dim cmd As New SqlCommand("DELETE FROM Emp WHERE employeeid =" + empid, cn) cn.Open() cmd.ExecuteNonQuery() cn.Close() End Sub 'DeleteRow
Dim myda As SqlDataAdapter Dim ds As DataSet Dim strConn As String Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here binddata() End Sub
Sub binddata() strConn = "Server=localhost;uid=sa;password=;database=northwind;" myconnection = New SqlConnection(strConn) myda = New SqlDataAdapter(SQLStmt, myconnection) ds = New DataSet myda.Fill(ds, "AllTables") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub
Protected Sub SortDataGrid(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) If ViewState("SortOrder") Is Nothing Then ViewState("SortOrder") = " ASC" ElseIf ViewState("SortOrder") = " ASC" Then ViewState("SortOrder") = " DESC" Else ViewState("SortOrder") = " ASC" End If SQLStmt = SQLStmt & " ORDER BY " & e.SortExpression & " " & ViewState("SortOrder") binddata() End Sub
C#
SqlConnection myconnection ; SqlDataAdapter myda ; DataSet ds ; String strConn ; string SQLStmt= "Select * from Products "; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here binddata(); }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Bind the Datagrid with dataSet End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Response.Write("You have selected :" & txtFname.Text) End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { //Bind the datagrid to dataset } private void Button1_Click(object sender, System.EventArgs e) { Response.Write("You have selected :" + txtFname.Text); }
25.26 How to add a TemplateColumn dynamically to the datagrid?
'Add constructor stuff here Public Sub InstantiateIn(ByVal container As Control) Implements System.Web.UI.ITemplate.InstantiateIn Dim label1 As New Label AddHandler label1.DataBinding, AddressOf Me.BindLabelColumn container.Controls.Add(label1) End Sub 'InstantiateIn
Public Sub BindLabelColumn(ByVal sender As Object, ByVal e As EventArgs) Dim lbl As Label = CType(sender, Label) Dim container As DataGridItem = CType(lbl.NamingContainer, DataGridItem) Dim strVals As [String] = Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, "LastName")) + ", " + Convert.ToString(DataBinder.Eval(CType(container, DataGridItem).DataItem, "FirstName")) lbl.Text = strVals End Sub 'BindLabelColumn End Class 'newLabelColumn
'Fill the Dataset Dim objtc As New TemplateColumn objtc.HeaderText = "Full Name" objtc.ItemTemplate = New newLabelColumn DataGrid1.Columns.Add(objtc) DataGrid1.DataSource = ds DataGrid1.DataBind()
C#
Create class
public class newLabelColumn : ITemplate { public newLabelColumn() { //Add constructor stuff here } public void InstantiateIn(Control container) { Label label1 = new Label(); label1.DataBinding += new EventHandler(this.BindLabelColumn); container.Controls.Add(label1); } public void BindLabelColumn(object sender, EventArgs e) { Label lbl = (Label)sender; DataGridItem container = (DataGridItem)lbl.NamingContainer ; String strVals = Convert.ToString(DataBinder.Eval(((DataGridItem)container).DataItem, "LastName")) + ", " +
Dim sqlStmt As String Dim conString As String Dim cn As SqlConnection Dim cmd As SqlCommand Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here If Not Page.IsPostBack Then BindGrid()
Sub BindGrid() 'Bind the Datagrid with dataSet End Sub 'BindGrid
Protected Sub EditCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex) BindGrid() End Sub 'EditCmd
Public Sub CancelCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = -1 BindGrid() End Sub 'CancelCmd
Protected Sub UpdateCmd(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) If Page.IsValid Then sqlStmt = "UPDATE Employees SET LastName = @LastName, FirstName=@FirstName,Title=@Title where EmployeeId = @EmployeeId" conString = "server=localhost;database=Northwind;uid=sa;pwd=;" cn = New SqlConnection(conString) cmd = New SqlCommand(sqlStmt, cn) Dim LastName, FirstName, Title As String LastName = CType(e.Item.FindControl("txtLastName"), TextBox).Text FirstName = CType(e.Item.FindControl("txtFirstName"), TextBox).Text Title = CType(e.Item.FindControl("txtTitle"), TextBox).Text Dim EmployeeId As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex)))
cmd.Parameters.Add(New SqlParameter("@LastName", LastName)) cmd.Parameters.Add(New SqlParameter("@FirstName", FirstName)) cmd.Parameters.Add(New SqlParameter("@Title", Title)) cmd.Parameters.Add(New SqlParameter("@EmployeeId", EmployeeId)) Try cn.Open() cmd.ExecuteNonQuery() DataGrid1.EditItemIndex = -1 Catch ex As Exception Response.Write(ex.Message.ToString()) End Try BindGrid() End If End Sub 'UpdateCmd
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { BindGrid(); } }
void BindGrid() { //Bind the DataGrid with dataset }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then BindDataGrid("ProductId") End If End Sub
Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) BindDataGrid(e.SortExpression.ToString()) End Sub
Sub BindDataGrid(ByVal sortfield As String) ViewState("SortExpression") = sortfield 'Fill the DataSet Dim dv As DataView = ds.Tables(0).DefaultView dv.Sort = sortfield DataGrid1.DataSource = dv DataGrid1.DataBind() End Sub
Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Dim dv As DataView = DataGrid1.DataSource Dim dc As DataColumnCollection = dv.Table.Columns If e.Item.ItemType = ListItemType.Header Then If ViewState("SortExpression") <> "" Then e.Item.Cells(dc.IndexOf(dc(ViewState("SortExpression")))).BackColor = Color.BlueViolet e.Item.Cells(dc.IndexOf(dc(ViewState("SortExpression")))).ForeColor = Color.AntiqueWhite End If End If End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(! Page.IsPostBack ) { BindDataGrid("ProductId"); } }
protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e ) { BindDataGrid(e.SortExpression.ToString()); }
protected void ItemDB(object sender ,System.Web.UI.WebControls.DataGridItemEventArgs e )
49
{ DataView dv =(DataView) DataGrid1.DataSource; DataColumnCollection dc = dv.Table.Columns; if (e.Item.ItemType == ListItemType.Header ) { if (ViewState["SortExpression"].ToString()!= "") { e.Item.Cells[dc.IndexOf( dc[ViewState["SortExpression"].ToString ()])].BackColor = Color.BlueViolet; e.Item.Cells[dc.IndexOf(dc[ViewState["SortExpression"].ToString ()])].ForeColor = Color.AntiqueWhite; } } }
25.30 How to create a Drilldown DataGrid?
Refer ASP.NET Reports Starter Kit DrillDown Overview
25.31 How to set a Datagrid Column to invisible when that Column is an AutoGeneratedColumn?
In the DataGrid's declaration, add the following code in OnItemDataBound event
VB.NET
Dim dv As DataView = DataGrid1.DataSource 'Bind you DataGrid1 in Page_Load to DataView Dim dc As DataColumnCollection = dv.Table.Columns e.Item.Cells(dc.IndexOf(dc("field_name))).Visible = false
C#
DataView dv = DataGrid1.DataSource ;//Bind you DataGrid1 in Page_Load to DataView DataColumnCollection dc = dv.Table.Columns; e.Item.Cells[dc.IndexOf(dc["field_name"])].Visible = false;
25.32 How to use the DataFormatString to format DataGrid data dynamically?
In the ItemDataBound Event of DataGrid write following code.
VB.NET
Dim ds As DataSet = CType(DataGrid1.DataSource, DataSet) Dim dv As DataView = ds.Tables(0).DefaultView Dim dcCol As DataColumnCollection = dv.Table.Columns If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then e.Item.Cells(dcCol.IndexOf(dcCol("UnitPrice"))).Text = DataBinder.Eval(e.Item.DataItem, "UnitPrice", "{0:c}") End If
Note : By doing a ViewSource you can find the Attribute Description for the Table that displays the DataGrid data
25.35 Why do I get the error message " CS1502: The best overloaded method match for 'xxx(string)' has some invalid arguments " when I use Helper function in DataGrid?
The function xxx() is expecting a string, but DataBinder.Eval() returns an object. So you must cast the result of
DataBinder.Eval() to a string (or, in this case, just use .ToString()).
Dim sqlStmt As String Dim conString As String Dim cn As SqlConnection = Nothing Dim da As SqlDataAdapter = Nothing Dim ds As DataSet
Private Sub Page_Load(sender As Object, e As System.EventArgs) conString = "server=localhost;database=Northwind;uid=sa;pwd=;" cn = New SqlConnection(conString) If Not Page.IsPostBack Then BindData() End If End Sub 'Page_Load
sqlStmt = "select * from emp " ds = New DataSet() da = New SqlDataAdapter(sqlStmt, cn) da.Fill(ds, "t1") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub 'BindData
Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs) Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem Dim btn As LinkButton = CType(e.Item.FindControl("btnDelete"), LinkButton) btn.Attributes.Add("onclick", "return confirmmsg();") Exit End Select End Sub 'ItemDB
Protected Sub ItemCmd(sender As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs) If e.CommandName = "Delete" Then Me.DeleteRow(Me.DataGrid1.DataKeys(e.Item.ItemIndex).ToString()) End If BindData() End Sub 'ItemCmd
Private Sub DeleteRow(empid As String) Dim cmd As New SqlCommand("DELETE FROM Emp WHERE employeeid =" + empid, cn) cn.Open() cmd.ExecuteNonQuery() cn.Close() End Sub 'DeleteRow
C#
string sqlStmt ; string conString ; SqlConnection cn =null; SqlDataAdapter da =null; DataSet ds; private void Page_Load(object sender, System.EventArgs e) { conString = "server=localhost;database=Northwind;uid=sa;pwd=;"; cn = new SqlConnection(conString); if (!Page.IsPostBack ) { BindData(); } } void BindData() { sqlStmt = "select * from emp "; ds= new DataSet (); da = new SqlDataAdapter (sqlStmt, cn); da.Fill (ds,"t1"); DataGrid1.DataSource =ds; DataGrid1.DataBind (); }
protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { switch(e.Item.ItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: { LinkButton btn = (LinkButton)e.Item.FindControl("btnDelete");
Dim strDiscontinued As String Dim obj As GetData Dim strSql As String Dim strConn As String Dim ds As DataSet Dim dr As SqlDataReader
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here strConn = "server=localhost;uid=sa;pwd=;database=northwind" If Not Page.IsPostBack Then BindGrid() End If End Sub 'Page_Load
'To Bind the DataGrid Sub BindGrid() obj = New GetData strSql = "Select productid, discontinued from Products" ds = obj.GetDataFromTable(strSql, strConn) DataGrid1.DataSource = ds DataGrid1.DataBind()
55
End Sub 'BindGrid
'To display Yes/No for True/False Protected Function ShowVal(ByVal blnval As Boolean) As String If blnval = True Then Return "Yes" Else Return "No" End If End Function 'ShowVal
'Bind the Data to the dropdownlist in the EditTemplate Protected Function BindTheDiscontinued() As SqlDataReader obj = New GetData strSql = "SELECT distinct 'Discontinued' =" strSql += " CASE " strSql += " WHEN Discontinued = 1 Then 'Yes'" strSql += " ELSE 'No'" strSql += " END " strSql += " From Products " dr = obj.GetSingleDataUsingReader(strSql, strConn) Return dr End Function 'BindTheDiscontinued
'Set the Text of the Dropdownlist to the field value in Database Protected Sub SetDropDownIndex(ByVal sender As [Object], ByVal e As System.EventArgs) Dim ed As DropDownList ed = CType(sender, DropDownList) ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued)) End Sub 'SetDropDownIndex
'For Edit Update Cancel Public Sub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) strDiscontinued = CType(e.Item.FindControl("lblDiscontinued"), Label).Text DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex) BindGrid() End Sub 'DataGrid1_Edit
Public Sub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) Dim TempList As DropDownList Dim TempValue As [String] TempList = CType(e.Item.FindControl("ddlDiscontinued"), DropDownList) TempValue = TempList.SelectedItem.Value 'Place update code here Response.Write(TempValue) DataGrid1.EditItemIndex = -1 BindGrid() End Sub 'DataGrid1_Update
Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = -1 BindGrid() End Sub 'DataGrid1_Cancel
'Functions used in Class GetData.cs Dim mycn As SqlConnection Dim myda As SqlDataAdapter Dim mycmd As SqlCommand Dim ds As DataSet Dim strConn As String Dim myReader As SqlDataReader
Public Function GetDataFromTable(ByVal strSQL As String, ByVal strConnString As String) As DataSet Try strConn = strConnString mycn = New SqlConnection(strConn) myda = New SqlDataAdapter(strSQL, mycn) ds = New DataSet myda.Fill(ds, "Table")
56
Return ds Catch ex As Exception Throw New Exception(ex.Message.ToString()) Finally mycn.Close() End Try End Function 'GetDataFromTable
Public Function GetSingleDataUsingReader(ByVal strSQL As String, ByVal strConnString As String) As SqlDataReader Try strConn = strConnString mycn = New SqlConnection(strConn) mycmd = New SqlCommand(strSQL, mycn) mycn.Open() myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection) Return myReader Catch ex As Exception Throw New Exception(ex.Message.ToString()) Finally End Try 'mycn.Close (); End Function 'GetSingleDataUsingReader
C#
string strDiscontinued; GetData obj; string strSql; string strConn; DataSet ds; SqlDataReader dr; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here strConn ="server=localhost;uid=sa;pwd=;database=northwind"; if (!Page.IsPostBack ) { BindGrid(); } }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Populate the Datagrid populating data from the database '..... End Sub
C#
int count =0; protected int getCount() { count = count + 1; return count; }
private void Page_Load(object sender, System.EventArgs e) { //Populate the Datagrid populating data from the database //.... }
25.41 How to change the HeaderText of the Datagrid?
Method 1 : Set the HeaderText Property of the BoundColumn/TemplateColumn
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Populate the DataGrid End Sub
protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Header Then e.Item.Cells(0).Text = "Employee ID" e.Item.Cells(1).Text = "First Name"
Dim cn As SqlConnection Dim da As SqlDataAdapter Dim cmd As SqlCommand Dim strsql As String Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;") If Not Page.IsPostBack Then BindData()
Sub BindData() DataGrid1.DataSource = GetData("Select * from Region") DataGrid1.DataBind() End Sub
Function GetData(ByVal strSql As String) As DataSet da = New SqlDataAdapter(strSql, cn) ds = New DataSet() da.Fill(ds) Return ds End Function
Protected Sub ItemCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) If e.CommandName = "Edit" Then 'Fill the Textboxes with relevant data FillTheData(e.Item.Cells(1).Text, e.Item.Cells(2).Text) End If End Sub
Sub FillTheData(ByVal RegionID As String, ByVal RegionDescription As String) txtRegionID.Text = RegionID txtRegionDescription.Text = RegionDescription End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click Try strsql = "Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId" cmd = New SqlCommand(strsql, cn) cmd.Parameters.Add(New SqlParameter("@RegionId", SqlDbType.Int)) cmd.Parameters.Add(New SqlParameter("@RegionDescription", SqlDbType.NVarChar, 40)) cmd.Parameters("@RegionId").Value = Convert.ToInt32(txtRegionID.Text) cmd.Parameters("@RegionDescription").Value = txtRegionDescription.Text cn.Open() cmd.ExecuteNonQuery() BindData() lblMessage.Text = "Updated Successfully" Catch ex As Exception lblMessage.Text = ex.Message lblMessage.ForeColor = Color.Red Finally cn.Close() End Try End Sub
C#
SqlConnection cn; SqlDataAdapter da ; SqlCommand cmd ; string strsql ; DataSet ds ; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here cn = new SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;"); if(!Page.IsPostBack) { //Code to Bind the data to the Datagrid BindData(); }
62
}
void BindData() { DataGrid1.DataSource = GetData("Select * from Region"); DataGrid1.DataBind(); } DataSet GetData(string strSql) { da = new SqlDataAdapter(strSql, cn); ds = new DataSet(); da.Fill(ds); return ds; }
protected void ItemCommand(Object source,System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Edit") { //'Fill the Textboxes with relevant data FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text); lblMessage.Text=""; } }
Private Sub Page_Load(sender As Object, e As System.EventArgs) ' Put user code to initialize the page here If Not Page.IsPostBack Then 'Populate the DataGrid End If End Sub 'Page_Load
Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then If e.Item.Cells(1).Text = " " Then e.Item.Cells(1).Text = "No data" End If End If End Sub 'ItemDB
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!Page.IsPostBack ) { //Populate the DataGrid } }
protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e ) { if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem)) { if( e.Item.Cells[1].Text == " ") { e.Item.Cells[1].Text = "No data"; }
Protected Sub ItemDB(ByVal s As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then Select Case Trim(e.Item.Cells(3).Text) Case "Sales Representative" e.Item.Cells(3).Text = "SR" Case "Vice President, Sales" e.Item.Cells(3).Text = "VP" Case "Sales Manager" e.Item.Cells(3).Text = "SM" Case "Inside Sales Coordinator" e.Item.Cells(3).Text = "ISC" Case Else e.Item.Cells(3).Text = e.Item.Cells(3).Text End Select end if end sub
C#
protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e ) { if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem)) { switch ( e.Item.Cells[3].Text.Trim() ) { case "Sales Representative": e.Item.Cells[3].Text = "SR"; break; case "Vice President, Sales": e.Item.Cells[3].Text = "VP"; break; case "Sales Manager": e.Item.Cells[3].Text = "SM"; break; case "Inside Sales Coordinator": e.Item.Cells[3].Text = "ISC"; break; default : e.Item.Cells[3].Text = e.Item.Cells[3].Text; break; } } }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then 'Populate the DataGrid End If End Sub
Protected Sub ItemCmd(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) If e.CommandName = "Show" Then Response.Write(e.Item.Cells(1).Text) End If End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { //Populate the DataGrid } }
protected void ItemCmd(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e ) { if (e.CommandName.ToString () == "Show") { Response.Write(e.Item.Cells[1].Text); } }
25.47 How to display a Master Detail data using DataGrid?
Dim cn As SqlConnection Dim da As SqlDataAdapter Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=northwind") If Not Page.IsPostBack Then da = New SqlDataAdapter("SELECT orderid FROM orders", cn) ds = New DataSet da.Fill(ds, "Orders") DataGrid1.DataSource = ds DataGrid1.DataBind() End If End Sub 'Page_Load
Protected Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then Dim dgDetails As New DataGrid Dim orderid As Integer = CInt(CType(e.Item.DataItem, DataRowView)("OrderID")) dgDetails.DataSource = GetOrderDetails(orderid) dgDetails.DataBind() e.Item.Cells(1).Controls.Add(dgDetails) End If End Sub 'ItemDB
Function GetOrderDetails(ByVal id As Integer) As DataSet da = New SqlDataAdapter("SELECT * FROM [Order Details] where orderid=" + id.ToString, cn) ds = New DataSet da.Fill(ds, "OrderDetails") Return ds End Function 'GetOrderDetails
C#
SqlConnection cn; SqlDataAdapter da; DataSet ds; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here cn= new SqlConnection ("Server=localhost;uid=sa;pwd=;database=northwind"); if (!Page.IsPostBack) { da= new SqlDataAdapter ("SELECT orderid FROM orders ", cn); ds= new DataSet (); da.Fill (ds, "Orders"); DataGrid1.DataSource = ds; DataGrid1.DataBind ();
67
} }
protected void ItemDB(Object sender,DataGridItemEventArgs e ) { if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem )) { DataGrid dgDetails = new DataGrid(); int orderid =(int) ((DataRowView)e.Item.DataItem)["OrderID"] ; dgDetails.DataSource = GetOrderDetails(orderid ); dgDetails.DataBind(); e.Item.Cells[1].Controls.Add(dgDetails); } }
DataSet GetOrderDetails(int id ) { da= new SqlDataAdapter ("SELECT * FROM [Order Details] where orderid= " + id, cn); ds= new DataSet (); da.Fill (ds, "OrderDetails"); return ds; }
25.48 I have set the ItemStyle and the AlternatingItemStyle tags for DataGrid control but they aren't working correctly , why?
DataGrid generates an HTML Table, with TableRows and Cells. If you already have some display properties set for
<td>,<TR>... make sure to check them in the Stylesheet. Whatever properties you set there will normally override
whatever you add into your DataGrid's Item styles.
25.49 How to display the checkbox checked or unchecked for a bit data type value in the DataBase?
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here If Not Page.IsPostBack Then BindGrid("") End If End Sub
Sub BindGrid(ByVal stralpha As String) Dim cn As SqlConnection Dim da As SqlDataAdapter Dim ds As DataSet cn = New SqlConnection("Server=localhost;uid=sa;pwd=;database=pubs") Dim strsql As String = "Select * from authors " If stralpha = "" Then strsql = strsql Else strsql = strsql + " where au_lname like'" + stralpha + "%'" End If da = New SqlDataAdapter(strsql, cn) ds = New DataSet da.Fill(ds, "Product") If (ds.Tables(0).Rows.Count = 0) Then Response.Write("No Data Found") DataGrid1.DataSource = Nothing DataGrid1.DataBind() Else DataGrid1.DataSource = ds DataGrid1.DataBind() End If End Sub
Protected Sub ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Footer Then e.Item.Cells.Clear() Dim tc As TableCell = New TableCell tc.ColumnSpan = 2 e.Item.Cells.Add(tc) Dim lc As LiteralControl Dim lb As LinkButton Dim i As Integer For i = 65 To 65 + 25 lc = New LiteralControl lb = New LinkButton lc.Text = " " lb.Text = Chr(i) lb.CommandName = "alpha" lb.CommandArgument = Chr(i) tc.Controls.Add(lb) tc.Controls.Add(lc) Next End If End Sub
Protected Sub ItemCommand(ByVal source As Object, ByVal e As
69
System.Web.UI.WebControls.DataGridCommandEventArgs) If (e.CommandName = "alpha") Then BindGrid(e.CommandArgument.ToString()) End If End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { BindGrid(""); } }
void BindGrid(string stralpha) { SqlConnection cn; SqlDataAdapter da; DataSet ds; cn = new SqlConnection ("Server=localhost;uid=sa;pwd=;database=pubs"); string strsql ="Select * from authors "; if (stralpha=="") { strsql = strsql ; } else { strsql = strsql + " where au_lname like'" + stralpha + "%'"; } da= new SqlDataAdapter (strsql,cn); ds= new DataSet (); da.Fill (ds, "Product"); if (ds.Tables [0].Rows.Count ==0) { Response.Write ("No Data Found"); DataGrid1.DataSource=null; DataGrid1.DataBind (); } else { DataGrid1.DataSource =ds; DataGrid1.DataBind (); } }
protected void ItemCreated(Object sender , System.Web.UI.WebControls.DataGridItemEventArgs e ) { if (e.Item.ItemType == ListItemType.Footer) { e.Item.Cells.Clear(); TableCell tc = new TableCell(); tc.ColumnSpan = 2; e.Item.Cells.Add(tc); LiteralControl lc; LinkButton lb; string s="" ; for (char c='A' ; c<= 'Z' ; ) { lc = newLiteralControl (); lb = new LinkButton (); s = c.ToString() ; lc.Text =" ";
Protected Function CheckStatus(ByVal prdStatus As Boolean) As Boolean If prdStatus = False Then Return True Else Return False End If End Function
C#
protected bool CheckStatus(bool prdStatus) { //If the Discontinued field is "0" if (prdStatus==false) { return true; } //If the Discontinued field is "1" else { return false;
Dim cn As SqlConnection Dim da As SqlDataAdapter Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind") da = New SqlDataAdapter("Select * from orders where orderid=10248", cn) ds = New DataSet() da.Fill(ds, "Orders") DataGrid1.DataSource = GoDoReShape(ds) DataGrid1.DataBind() End Sub 'Page_Load
Public Function GoDoReShape(ByVal ds As DataSet) As DataSet Dim NewDs As New DataSet()
NewDs.Tables.Add() 'Create Two Columns with names "ColumnName" and "Value" 'ColumnName -> Displays all ColumnNames 'Value -> Displays ColumnData NewDs.Tables(0).Columns.Add("ColumnName") NewDs.Tables(0).Columns.Add("Value")
Dim dr As DataRow For Each dr In ds.Tables(0).Rows Dim dcol As System.Data.DataColumn For Each dcol In ds.Tables(0).Columns 'Declare Array Dim MyArray As String() = {dcol.ColumnName.ToString(), dr(dcol.ColumnName.ToString()).ToString()} NewDs.Tables(0).Rows.Add(MyArray) Next Next Return NewDs End Function 'GoDoReShape
C#
SqlConnection cn ; SqlDataAdapter da; DataSet ds;
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here cn =new SqlConnection("server=localhost;uid=sa;pwd=;database=northwind"); da=new SqlDataAdapter ( "Select * from orders where orderid=10248",cn);
Dim mycn As SqlConnection Dim myda As SqlDataAdapter Dim ds As DataSet Dim strConn, strSQL As String
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=;" If Not Page.IsPostBack Then BindGrid() End If End Sub 'Page_Load
Sub BindGrid() mycn = New SqlConnection(strConn) strSQL = "Select * from [Order Details] where orderid=10249" myda = New SqlDataAdapter(strSQL, mycn) ds = New DataSet myda.Fill(ds, "Table") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub 'BindGrid
Public Sub DataGrid1_Cancel(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = -1 BindGrid() End Sub 'DataGrid1_Cancel
Public Sub DataGrid1_Edit(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex) BindGrid() End Sub 'DataGrid1_Edit
Public Sub DataGrid1_Update(ByVal sender As [Object], ByVal e As DataGridCommandEventArgs) Dim unitprice As String = CType(e.Item.Cells(3).Controls(0), TextBox).Text Dim quantity As String = CType(e.Item.Cells(4).Controls(0), TextBox).Text Dim discount As String = CType(e.Item.Cells(5).Controls(0), TextBox).Text Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex))) Dim productid As String = CType(e.Item.Cells(2).Controls(0), TextBox).Text
Try Dim updateCmd As String = "UPDATE [Order Details] SET UnitPrice = @UnitPrice," + "Quantity = @Quantity, Discount = @Discount where OrderId =@OrderId and ProductId=@ProductId"
Dim cn As New SqlConnection(strConn) Dim myCommand As New SqlCommand(updateCmd, cn) myCommand.Parameters.Add(New SqlParameter("@UnitPrice", Convert.ToDecimal(unitprice))) myCommand.Parameters.Add(New SqlParameter("@Quantity", Convert.ToInt16(quantity))) myCommand.Parameters.Add(New SqlParameter("@Discount", Convert.ToInt16(discount))) myCommand.Parameters.Add(New SqlParameter("@OrderId", orderid)) myCommand.Parameters.Add(New SqlParameter("@ProductId", Convert.ToInt16(productid))) cn.Open() myCommand.ExecuteNonQuery() DataGrid1.EditItemIndex = -1 BindGrid() Catch ex As Exception lblError.Visible = True lblError.Text = ex.Message End Try End Sub 'DataGrid1_Update
Dim mycn As SqlConnection Dim myda As SqlDataAdapter Dim ds As DataSet Dim strConn, strSQL As String
Private Sub Page_Load(sender As Object, e As System.EventArgs) strConn = "server=localhost;uid=sa;database=northwind;pwd=;" If Not Page.IsPostBack Then BindGrid() End If End Sub 'Page_Load
Sub BindGrid() mycn = New SqlConnection(strConn) strSQL = "Select * from Region" myda = New SqlDataAdapter(strSQL, mycn) ds = New DataSet() myda.Fill(ds, "Table") DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub 'BindGrid
Public Sub DataGrid1_Cancel(sender As [Object], e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = - 1 BindGrid() End Sub 'DataGrid1_Cancel
Public Sub DataGrid1_Edit(sender As [Object], e As DataGridCommandEventArgs) DataGrid1.EditItemIndex = CInt(e.Item.ItemIndex) BindGrid() End Sub 'DataGrid1_Edit
Public Sub DataGrid1_Delete(sender As [Object], e As DataGridCommandEventArgs) Dim orderid As Integer = CInt(DataGrid1.DataKeys(CInt(e.Item.ItemIndex))) Dim deleteCmd As [String] = "DELETE from Region where Regionid = @Regionid " Dim cn As New SqlConnection(strConn) Dim myCommand As New SqlCommand(deleteCmd, cn) myCommand.Parameters.Add(New SqlParameter("@Regionid", SqlDbType.Int)) myCommand.Parameters("@Regionid").Value = DataGrid1.DataKeys(CInt(e.Item.ItemIndex)) myCommand.Connection.Open() Try myCommand.ExecuteNonQuery() Catch lblError.Text = "ERROR: Could not delete record" End Try myCommand.Connection.Close() BindGrid() End Sub 'DataGrid1_Delete
Protected Sub ItemCmd(source As Object, e As System.Web.UI.WebControls.DataGridCommandEventArgs) If e.CommandName.ToString() = "Show" Then Response.Write(e.Item.Cells(5).Text) End If End Sub 'ItemCmd
C#
protected void ItemCmd(Object source, System.Web.UI.WebControls.DataGridCommandEventArgs e ) {
Protected Function GetURL(ByVal fldval As String) As String If fldval.IndexOf("http://", 0, fldval.Length) = 0 Then Return fldval Else Return "http://" + fldval End If End Function 'GetURL
25.61 How to display a Tooltip when hovering over the Header sort link of the DataGrid?
Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs) Dim i As Integer For i = 0 To e.Item.Cells.Count - 1 e.Item.Cells(i).ToolTip = "This is Column " + i.ToString() Next End Sub 'ItemDB
25.63 How to hide a row in a DataGrid if one of the Column value is zero?
VB.NET
Protected Sub ItemDB(sender As Object, e As System.Web.UI.WebControls.DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.Item Then If e.Item.Cells(8).Text = "0" Then e.Item.Visible = False End If End If End Sub 'ItemDB
protected Sub dgPreRender(ByVal sender As Object, ByVal e As System.EventArgs) Dim dgItem As New DataGridItem(0, 0, ListItemType.Header) Dim tbCell As New TableCell tbCell.ColumnSpan = 3 'Set it to the colspan that you want tbCell.Text = "Category Information" tbCell.Attributes.Add("style", "text-align:center") dgItem.Cells.Add(tbCell) DataGrid1.Controls(0).Controls.AddAt(0, dgItem) End Sub
C#
protected void dgPreRender(object sender, System.EventArgs e ) { DataGridItem dgItem = new DataGridItem (0, 0, ListItemType.Header); TableCell tbCell = new TableCell(); tbCell.ColumnSpan = 3;// Set it to the colspan that you want tbCell.Text = "Category Information";
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not IsPostBack Then 'Populate the datagrid End If End Sub
protected Sub chkChanged(ByVal sender As Object, ByVal e As System.EventArgs) Response.Write("CheckChanged Event") End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { DataGrid1.DataSource =BindDataClass.BindData (); DataGrid1.DataBind (); } }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here If Not Page.IsPostBack Then 'Populate the dataSet 'Bind the dataGrid with the dataView DataGrid1.DataSource = BindTheDataClass.Binddata().Tables(0).DefaultView DataGrid1.DataBind() End If End Sub 'Page_Load
Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Dim dv As DataView = CType(DataGrid1.DataSource, DataView) Dim drv As DataRowView = CType(e.Item.DataItem, DataRowView) If dv.Table.Rows.Count = 0 Then 'By default the Datagrid Header is shown in case there is no Data Avaiable 'So in case of No Data found 'Check the ListItemType.Header If e.Item.ItemType = ListItemType.Header Then Dim i As Integer = e.Item.Cells.Count
'Assign "No Search result Found" in one of the cells of DataGrid e.Item.Cells(0).Text = "No Search Results Found"
'Remove Rest of the empty cells from Datagrid Dim j As Integer For j = i - 1 To 1 Step -1 e.Item.Cells.RemoveAt(j) Next End If End If End Sub 'ItemDB
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!Page.IsPostBack ) { //Fill DataSet //Bind the DataGrid with the DataView DataGrid1.DataSource =ds.Tables[0].DefaultView ; DataGrid1.DataBind (); } }
protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) { DataView dv =(DataView)DataGrid1.DataSource ; DataRowView drv = (DataRowView)e.Item.DataItem ; if (dv.Table.Rows.Count == 0 ) { //By default the Datagrid Header is shown in case there is no Data Avaiable //So in case of No Data found //Check the ListItemType.Header if ((e.Item.ItemType == ListItemType.Header))
85
{ int i= e.Item.Cells.Count;
//Assign "No Search result Found" in one of the cells of DataGrid e.Item.Cells [0].Text = "No Search Results Found";
//Remove Rest of the empty cells from Datagrid for (int j=i-1;j>0;j--) { e.Item.Cells.RemoveAt(j); } } } }
'Fill the DataSet ds with data from database Dim dc As DataColumn dc = New DataColumn("Total", Type.GetType("System.Double")) dc.Expression = "UnitPrice * UnitsInStock" ds.Tables(0).Columns.Add(dc)
//Fill the DataSet ds with data from database DataColumn dc ; dc = new DataColumn("Total", Type.GetType("System.Double")); dc.Expression = "UnitPrice * UnitsInStock"; ds.Tables[0].Columns.Add(dc);
DataGrid1.DataSource = ds; DataGrid1.DataBind();
25.75 How to access the BoundColumn information on SelectedIndexChanged event of a datagrid?
Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = DataGrid1.SelectedItem.Cells(1).Text & DataGrid1.SelectedItem.Cells(2).Text End Sub
Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = CType(DataGrid1.SelectedItem.Cells(1).Controls(0), DataBoundLiteralControl).Text & CType(DataGrid1.SelectedItem.Cells(2).Controls(0), DataBoundLiteralControl).Text End Sub
Protected Sub SelectedIndexChg(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = CType(DataGrid1.SelectedItem.FindControl("lbl1"), Label).Text End Sub
Dim UnitPrice As Double Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here 'Bind the Data to datagrid End Sub
Protected Sub UPTotal(ByVal _unitprice As Double) UnitPrice += _unitprice End Sub 'UPTotal
Public Sub ItemDB(ByVal sender As Object, ByVal e As DataGridItemEventArgs) If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then UPTotal(Double.Parse(e.Item.Cells(1).Text.ToString)) Else If e.Item.ItemType = ListItemType.Footer Then e.Item.Cells(0).Text = " Total " e.Item.Cells(1).Text = UnitPrice.ToString() End If End If End Sub 'ItemDB
C#
double UnitPrice; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!Page.IsPostBack ) { //Bind the DataGrid } } protected void UPTotal(double _unitprice) { UnitPrice += _unitprice; }
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then 'Bind the dataGrid to DataView End If End Sub
Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Dim dv As DataView = DataGrid1.DataSource Dim dcCol As DataColumn Dim dc As DataColumnCollection = dv.Table.Columns Dim strID As String For Each dcCol In dv.Table.Columns If e.Item.ItemType = ListItemType.AlternatingItem Or _ e.Item.ItemType = ListItemType.Item Then strID = DataGrid1.DataKeys(e.Item.ItemIndex) e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add("style", "cursor:hand") e.Item.Cells(dc.IndexOf(dc(dcCol.ColumnName))).Attributes.Add("onclick", _ "javascript:window.open('details.aspx?id=" & strID & "'," _ & "'MyPage','height=300,width=300')")
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if(!Page.IsPostBack ) { //Bind Datagrid to DataView } }
25.81 How should I avoid getting blank page on click of linkbutton inspite of setting the EnableViewState= true for DataGrid?
You should bind the data each time the page is loaded
25.82 Why do I get a blank page when I click the linkbutton in the Datagrid, I am also handling PostBack on the page? The ItemCommand Event does not seem to trigger?
You must have set the EnableViewState property of DataGrid to false
25.83 How to export data in Datagrid on a webform to Microsoft Excel?
Two techniques for exporting the data in the DataGrid:
Using the Excel MIME Type (or Content Type)
With server-side code, you can bind the DataGrid to your data and have the data open in Excel on a client
computer. To do this, set the ContentType to application/vnd.ms-excel. After the client receives the new
stream, the data appears in Excel as if the content was opened as a new page in the Web browser.
Using Excel Automation
With client-side code, you can extract the HTML from the DataGrid and then Automate Excel to display the
HTML in a new workbook. With Excel Automation, the data always appears outside the browser in an Excel
application window. One advantage to Automation is that you can programmatically control Excel if you
want to modify the workbook after the data is exported. However, because Excel is not marked as safe for
scripting, your clients must apply security settings in the Web browser that allow Automation.
For more details refer How To Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel
25.84 How to export DataGrid data to excel?
Use namespace System.IO
VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here 'Bind the DataGrid to DataSet DataGridToExcel(DataGrid1, Response) End Sub
Protected Sub DataGridToExcel(ByVal dGridExport As DataGrid, ByVal httpResp As HttpResponse) httpResp.Clear() httpResp.Charset = "" httpResp.ContentType = "application/vnd.ms-excel" Dim stringWrite As New StringWriter Dim htmlWrite As New HtmlTextWriter(stringWrite) Dim dGrid As New DataGrid dGrid = dGridExport dGrid.HeaderStyle.Font.Bold = True dGrid.DataBind() dGrid.RenderControl(htmlWrite) httpResp.Write(stringWrite.ToString) httpResp.End() End Sub
C#
private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here //Bind the DataGrid to DataSet DataGridToExcel (DataGrid1, Response); } protected void DataGridToExcel(DataGrid dGridExport , HttpResponse httpResp) { httpResp.Clear(); httpResp.Charset = ""; httpResp.ContentType = "application/vnd.ms-excel"; StringWriter stringWrite = new StringWriter();
27.1 How do I insert custom @ Register tags into the aspx file from my custom control?
In the custom control's custom designer's Initialize override, do something like this:
[C#] public override void Initialize(IComponent component) {
base.Initialize (component);
IDesignerHost host = component.Site.Container as IDesignerHost; IDesigner designer = host.GetDesigner(host.RootComponent);
// Calling GetHTMLFromWebControlTool with the following custom toolboxitem will insert the // Register directives for the type associated with that . MethodInfo mi = designer.GetType.GetMethod("GetHTMLFromWebControlTool", BindingFlags.NonPublic | BindingFlags.Instance); if(mi != null) { // DependantType is a custom type defined in DependantAssembly.dll mi.Invoke(designer, new object[]{new WebControlToolboxItem(typeof(SomeNamespace.DependantType))}); } }
C Then when the user drags and drops the item from the toolbox, besides the default @ register entry it makes, it
will also make an entry like this: <%@ Register TagPrefix="cc1" Namespace="SomeNamespace"
Protected function TruncateData( Byval strNotes as string) If strNotes.Length > 20 then Return strNotes.Substring(0,20) + "..." Else return strnotes End function
31.8 How to Implement a DataSet SELECT DISTINCT Helper Class?
VB.NET
Sample code 1
C#
Sample Code 2
31.9 I am running the query SQL="Select name from profile where proID=1"; and I am getting the result in Dataset dsdata. Now how do I read the text from the dataset and assign it to textbox1.text ?
VB.NET
dsData.Tables(0).Rows(0)("FieldName").ToString()
C#
dsData.Tables[0].Rows[0]["FieldName"].ToString()
31.10 How to query the database to get all the Table names?
SELECT * FROM information_schema.tables where Table_type='BASE TABLE'
'Put user code to initialize the page here Try 'Fill the DataSet If Not Page.IsPostBack Then ViewState("CurrentPos") = 0 Me.DataBind() End If Catch ex As Exception Response.Write(ex.Message & ex.StackTrace) End Try End Sub
protected Sub NextBtn(ByVal sender As System.Object, ByVal e As System.EventArgs) Try Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer) CurrentPos += 1 If CurrentPos > ds.Tables(0).Rows.Count Then CurrentPos -= 1 End If ViewState("CurrentPos") = CurrentPos Me.DataBind() Catch ex As Exception Response.Write(ex.Message) End Try End Sub
protected Sub PrevBtn(ByVal sender As System.Object, ByVal e As System.EventArgs) Try Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer) If CurrentPos > 0 Then CurrentPos -= 1 End If ViewState("CurrentPos") = CurrentPos Me.DataBind() Catch ex As Exception Response.Write(ex.Message) End Try End Sub
protected Sub txtDataBind(ByVal sender As Object, ByVal e As System.EventArgs) Try Dim CurrentPos As Integer = CType(ViewState("CurrentPos"), Integer) ViewState("CurrentPos") = (CurrentPos) txtProductid.Text = ds.Tables(0).Rows(CurrentPos).Item("productid") txtProductName.Text = ds.Tables(0).Rows(CurrentPos).Item("productname") Catch ex As Exception Response.Write(ex.Message) End Try End Sub
C#
DataSet ds; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here //Fill the DataSet if (!Page.IsPostBack ) { ViewState["CurrentPos"] = 0 ; this.DataBind() ; } } protected void PrevBtn(object sender, System.EventArgs e) {
Use namespaces System.Data.SqlClient, System.Data.SqlTypes
On Button Click
VB.NET
Dim sqlStmt As String Dim conString As String Dim cn As SqlConnection Dim cmd As SqlCommand Dim sqldatenull As SqlDateTime Try sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) " conString = "server=localhost;database=Northwind;uid=sa;pwd=;" cn = New SqlConnection(conString) cmd = New SqlCommand(sqlStmt, cn)
31.13 When I try to enter a null value for DataTime in Database I get error message "String was not recognized as a valid DateTime" or "Value of type 'System.DBNull' cannot be converted to 'String'"?
Use namespace
System.Data.SqlTypes
VB.NET
Dim sqldatenull As SqlDateTime sqldatenull = SqlDateTime.Null
Dim ds As New DataSet Dim myda As SqlDataAdapter = New SqlDataAdapter("GetSuppliers", "server=localhost;database=Northwind;uid=sa;pwd=;") myda.SelectCommand.CommandType = CommandType.StoredProcedure myda.Fill(ds, "Table") Dim slist As SortedList = New SortedList Dim dr As DataRow For Each dr In ds.Tables(0).Rows If Not slist.ContainsValue(dr("Country")) Then slist.Add(dr("Supplierid"), dr("Country")) End If Next DataList1.DataSource = slist.GetValueList DataList1.DataBind() 'In case of Dropdownlist 'DropDownList1.DataSource = slist.GetValueList 'DropDownList1.DataBind()
C#
DataSet ds = new DataSet(); SqlDataAdapter myda = new SqlDataAdapter("GetSuppliers", "server=localhost;database=Northwind;uid=sa;pwd=;"); myda.SelectCommand.CommandType = CommandType.StoredProcedure; myda.Fill(ds, "Table"); SortedList slist = new SortedList();
foreach( DataRow dr in ds.Tables[0].Rows) { if (! slist.ContainsValue(dr["Country"])) { slist.Add(dr["Supplierid"].ToString (), dr["Country"].ToString ()); } } DataList1.DataSource = slist.GetValueList(); DataList1.DataBind(); //In case of DropDownList //DropDownList1.DataSource = slist.GetValueList //DropDownList1.DataBind()
31.16 A field with bit data type value when displayed on a web page shows true/ false how to display a bit value as 1/0?
VB.NET
'Using DataReader While dr.Read() Response.Write((dr("ProductName") + " ")) Response.Write((Convert.ToInt16(dr("discontinued")) + " ")) End While
31.17 When I try to enter null value to DateTime field in database it is saved as 1/1/1900 12:00:00 AM?
Refer When I try to enter null value for DataTime in Database I get error message "String was not recognized as a
valid DateTime" or "Value of type 'System.DBNull' cannot be converted to 'String'"
31.18 How to use Stored Procedures in ASP.NET?
Refer Store Procedure Sample
31.19 How to display multiple records using DataTable.Select?
Use namespace System.Data.OleDb VB.NET
Dim myConnection As New OleDbConnection("Provider=SQLOLEDB.1;Data Source=localhost;database=northwind;User Id=sa;Password=;") Dim myda As New OleDbDataAdapter("Select * from Orders", myConnection) Dim ds = New DataSet myda.Fill(ds, "table")
Dim dr() As DataRow Dim id As String = "ROMEY" ' "Field with id ROMEY has more than one records found Dim sel As String = "customerid='" + id + "'" dr = ds.Tables(0).Select(sel) Dim i As Integer For i = 0 To (dr.GetUpperBound(0)) - 1 Response.Write((dr(i)("Orderid").ToString() + ControlChars.Tab + dr(i)("Customerid").ToString() + ControlChars.Tab + dr(i)("Freight").ToString() + "")) Next
C#
OleDbConnection myConnection = new OleDbConnection("Provider=SQLOLEDB.1;Data Source=localhost;database=northwind;User Id=sa;Password=;"); OleDbDataAdapter myda= new OleDbDataAdapter ("Select * from Orders", myConnection); System.Data.DataSet ds= new DataSet (); myda.Fill (ds,"table");
DataRow[] dr ; string id ="ROMEY";// "Field with id ROMEY has more than one records found string sel ="customerid='"+ id + "'"; dr = ds.Tables [0].Select (sel); int i; for(i=0;i{ Response.Write (dr[i]["Orderid"].ToString() + "\t" +
31.20 How to get the count of items in a dataReader?
VB.NET
Dim mycn As New SqlConnection("server=localhost;uid=sa;password=;database=northwind;") Dim mycmd As New SqlCommand("Select * from Products", mycn) mycn.Open() Dim dr As SqlDataReader = mycmd.ExecuteReader Dim i As Integer While dr.Read i += 1 End While Response.Write("Count of Records : " & i)
C#
SqlConnection mycn =new SqlConnection("server=localhost;uid=sa;password=;database=northwind;"); SqlCommand mycmd = new SqlCommand ("Select * from Products", mycn); mycn.Open(); SqlDataReader dr = mycmd.ExecuteReader(); int i=0; while(dr.Read()) { i+=1; } Response.Write("Count of Records : " + i.ToString());
31.21 How to check EOF with SqlDataReader?
If you are using the Framework 1.1 , use HasRows
For Framework < 1.1
VB.NET
Dim myconnection As SqlConnection Dim mycmd As SqlCommand Dim strSql As String Dim myReader As SqlDataReader
myconnection = New SqlConnection("Server=localhost;uid=sa;password=;database=northwind;") strSql = "Select count(*) from employees;Select * from employees" mycmd = New SqlCommand(strSql, myconnection) myconnection.Open() Dim count As Integer = CInt(mycmd.ExecuteScalar()) myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection) If count = 0 Then Response.Write("No records found")
Dim ds As New DataSet ds.ReadXml(Server.MapPath("data1.xml")) Dim dv As New DataView dv = ds.Tables(0).DefaultView dv.RowFilter = "prodId='product2-00'"
For SqlConnection we do not provide a Provider . Provider is used in cases where OleDbConnection is used.
31.26 Why do I get the error message "ExecuteReader: Connection property has not been initialized"?
This error is caused if there is no Connection object associated with the Command Object. To resolve this
VB.NET
Dim cn as new SqlConnection("<your connection string>") 'Dim cn as new OleDbConnection("<your connection string>") Dim cmd As new SqlCommand("Select * from Products", cn) 'Dim cmd As new OleDbCommand("Select * from Products", cn)
C#
SqlConnection cn = new SqlConnection ("<your connection string>"); 'OleDbConnection cn = new OleDbConnection ("<your connection string>"); SqlCommand cmd = new SqlCommand ("Select * from Products", cn); 'OleDbCommand cmd = new OleDbCommand ("Select * from Products", cn);
31.27 Why do I get the error message "There is already an open DataReader associated with this Connection which must be closed first."?
This is caused if you are attempting to use the same DataReader more than once in your code without closing the
previous Datareader. Or you might have a DataReader open on the same connection as the DataAdapter/Command
uses. So it is not recommended to share a connection between a DataReader and a DataAdapter/Command
Either close the first connection or,
if you must keep it open as you are executing another reader from within it, use another connection object.
31.28 I get the error message "Cast from type DBNull to type String is not valid." when I try to display DataReader values on form?
31.31 How to use the Same DataReader to populate two different ListBoxes?
You cannot use the same DataReader to populate 2 Listboxes.But can try out the below workaround
VB.NET
... cn = New SqlConnection("Server=localhost;uid=sa;database=northwind;pwd=") cmd = New SqlCommand("select * from products;select * from products", cn) cn.Open() dr = cmd.ExecuteReader() ListBox1.DataSource = dr ListBox1.DataTextField = "productname" ListBox1.DataBind() dr.NextResult() ListBox2.DataSource = dr ListBox2.DataTextField = "productname" ListBox2.DataBind()
You have to supply the Sql Statement or Stored Procedure for the DataAdapter as
VB.NET
da.SelectCommand.CommandText = "Select * from "
or
da = new SqlDataAdapter ("Select * from ", cn)
C#
da.SelectCommand.CommandText ="Select * from ";
or
da = new SqlDataAdapter ("Select * from ", cn);
31.35 How to use OleDb DataSet?
Use namespace System.Data.OleDb
VB.NET
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") & ";" Dim strsql As String = "Select * from Customers" Dim cn As New OleDbConnection(strConn) Dim ds As DataSet = New DataSet() Dim da As New OleDbDataAdapter(strsql, cn) da.Fill(ds, "T1") DataGrid1.DataSource = ds DataGrid1.DataBind()
C#
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";"; string strsql = "Select * from Customers"; OleDbConnection cn = new OleDbConnection(strConn); DataSet ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, cn); da.Fill(ds, "T1"); DataGrid1.DataSource = ds; DataGrid1.DataBind();
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") & ";" Dim strsql As String = "Select * from Customers" Dim cn As New OleDbConnection(strConn) Dim cmd As New OleDbCommand(strsql, cn) cn.Open() Dim dr As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) DataGrid1.DataSource = dr DataGrid1.DataBind()
C#
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";"; string strsql = "Select * from Customers"; OleDbConnection cn = new OleDbConnection(strConn); OleDbCommand cmd = new OleDbCommand (strsql, cn); cn.Open (); OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection ); DataGrid1.DataSource = dr; DataGrid1.DataBind();
31.37 How to loop through a Dataset to display all records?
VB.NET
'Fill Dataset Dim dc As DataColumn Dim dr As DataRow For Each dr In ds.Tables(0).Rows For Each dc In ds.Tables(0).Columns Response.Write(dr(dc.ColumnName).ToString()) Next Next
C#
//Fill the DataSet foreach (DataRow dr in ds.Tables[0].Rows) { foreach( DataColumn dc in ds.Tables[0].Columns) { Response.Write(dr[dc.ColumnName].ToString()); } }
32.15 Is the session timeout attribute in minutes or seconds?
The Timeout setting is in minutes, not in seconds. i.e The timeout attribute specifies the number of minutes a session
can be idle before it is abandoned. The default is 20
32.16 Will my session state be saved when my page hit an error? Will my session state be saved when my page hit an error? In Session_End, I tried to do some cleanup job using SQL but it failed. Why?
1. Session_End is supported only in InProc mode.
2. Session_End is run using the account which runs the worker process (aspnet_wp.exe), which can be
specified in machine.config. Therefore, in your Session_End, if you connect to SQL using integrated security,
it will use that worker process account credential to connect, and may fail depending on your SQL security
settings.
32.17 Why do I lose my Session variables on redirect when I set "cookieless" to true?
When using cookieless, you must use relative path (e.g. ..\webform1.aspx) instead of absolute path (e.g. \dir1\
subdir1\webform1.aspx). If you use absolute path, ASP.NET cannot preserve your session ID in the URL.
32.18 How to store SortedList in Session or Cache?
VB.NET
Dim x As New SortedList() x.Add("Key1", "ValueA") x.Add("Key2", "ValueB")
To store in Session:
Session("SortedList1") = x
and to retrieve
Dim y As SortedList = CType(Session("SortedList1"), SortedList)
SortedList x = new SortedList(); x.Add("Key1", "ValueA"); x.Add("Key2", "ValueB");
To store in Session:
Session["SortedList1"] = x;
and to retrieve
SortedList y = (SortedList) Session["SortedList1"];
32.19 Why do I get the error message "Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive"?
This problem may occur after you install Windows Sharepoint Server(WSS) on a server that has Microsoft Visual
Studio .NET 2003 installed. The WSS ISAPI filter handles all incoming URLs. When you browse one of the ASP.NET
Web application virtual directories, the ISAPI filter does not locate the URL path of the folder.
To resolve this refer Session state cannot be used in ASP.NET with Windows SharePoint Services
32.20 How to remove a Session variable?
Use HttpSessionState.Remove()
32.21 Is there any way to know how much memory is being used by session variables in my application?
No
32.22 I have a frameset page which has an HTM extension, and I found out that each frame it contains displays a different session id on the first request. Why?
The reason is that your frameset page is an HTM file instead of an ASPX file.
In normal a scenario, if the frameset is an aspx file, when you request the page, it will first send the request to the
web server, receive an asp.net session cookie (which holds the session id), and then the browser will send individual
requests for the frames, and each request will carry the same session id.