Using Gridview to display Images from Database
In ASP.Net 1.x days, Datagrid is one of the most widely used control to display a table of data. With the introduction of ASP.Net 2.0, we have Gridview in the place of Datagrid while the Datagrid control is still supported. With Gridview, we can prevent some of the standard codes we will repeat for edit, update, delete, sort operations.
As we all know, displaying an image stored in a database in Gridview is bit complicated and not a straight forward task. I will use the power of HttpHandler to do this task easily. Before moving to the HttpHandler implementation, this article will discuss the implemention of image storage in the database.
| |||||
| |||||
The output will be like,
|
shaaz logic
Followers
Sunday, 3 February 2013
Thursday, 24 January 2013
UML HOSPITAL MANAGEMENT SYSTEM
The hospital has several specialized departments like Cardiology, Gynecologic, Orthopedics, Pediatrics, ENT etc. OPD is another independent department. A doctor is only associated with one specialized department at a time though he/she can be a member of the OPD(Outside Patients Department) department. Each doctor has a visiting time and day in a week.
At
reception the patient details are entered and the fees are also taken and the
patient is tracked on the basis of the Id generated.
In
routine a patient can visit the doctors either directly selecting a doctor or
by getting admitted to the hospital and then a doctor visits the patients.
A
doctor can prescribe tests for the patient to perform. The patient visits the
lab to get done the tests prescribed by his/her doctor. The reports are given
to the patient. The payments pertaining to the tests are done at the reception.
Referring the reports, the doctor prescribes the patient medicines or further
tests or is asked to get admitted.
A
patient is admitted into a ward of a specialized department (if available) as
per the doctor’s prescription. The number of wards is limited and if there is
no vacant ward the admission of the patient is rescheduled.
As
per the prescription of the doctor the patient is operated on a specified date
and time as decided by the doctor who is doing the operation.
After the completion of the treatment a patient
may get discharged on an advice of a doctor and upon the complete payment of
all due charges at the reception. On payment of full dues the reception
generates a discharge ticket for the patient
Use Case Diagram:-
Class Diagram:-
Activity Diagram Registration :-
Activity Diagram for Ward Allocation:-
Activity Diagram for Tests to Perform:-
Activity Diagram for Treatment and Operations:-
Activity Diagram Discharge:-
State Chart Diagram for Patient:-
State Diagram for Doctor:-
State Diagram for Ward Object:-
Sequence Diagram for Patient Admit / Registration:-
Sequence Diagram Test & Operation:-
Sequence Diagram Discharge from Hospital :-
Collaboration Diagram Admit to Hospital:-
Collaboration Diagram for Treatment at Hospital:-
Collaboration Diagram for Discharge from Hospital :-
Sunday, 20 January 2013
Dynamically adding and deleting rows from ASP.NET GridView
Introduction
This article talks about a small project that presents the idea of having aGridView
which facilitate the addition and removal of rows dynamically at run time. Background
There are many times when we need the user to enter some data but we are not sure about the amount of data. For instance, we need to have an application that takes the student details from a faculty member(possibiliy at the time of admission). We can design this page in two ways i.e. either we take data of 1 student at a time or we allow the user to enter data of multiple users in single go. Also we can let the user choose the number of record he want to enter.Now to accomplish this if we design the page in such a way that the user will have the possibility of add adding new rows dynamically and then enter the data. How can we do that will be the focus of rest of the article.
Using the code
Let us first design the layout for taking a single record from the user.Now this design has been achieved by having the template fields in the
Gridview
in the following manner.
Collapse | Copy Code
<asp:GridView ID="grvStudentDetails" runat="server"
ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Age">
<ItemTemplate>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Address">
<ItemTemplate>
<asp:TextBox ID="txtAddress" runat="server"
Height="55px" TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:RadioButtonList ID="RBLGender"
runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="M">Male</asp:ListItem>
<asp:ListItem Value="F">Female</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qualification">
<ItemTemplate>
<asp:DropDownList ID="drpQualification" runat="server">
<asp:ListItem Value="G">Graduate</asp:ListItem>
<asp:ListItem Value="P">Post Graduate</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Now the basic idea here is that from code behind if we dynamically change the DataSource
of this Gridview
the grid view will change accordingly. So what we will do is that we
will have a single row exposed as default and then keep adding
rows in the Gridview
whenever the user requests to add a new row. For that we will simply keep adding empty data items
to the Gridview
adta source resulting in the Gridview
getting changed dynamically.Let us see the code to have a default single row
private void FirstGridViewRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
dt.Columns.Add(new DataColumn("Col4", typeof(string)));
dt.Columns.Add(new DataColumn("Col5", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Col1"] = string.Empty;
dr["Col2"] = string.Empty;
dr["Col3"] = string.Empty;
dr["Col4"] = string.Empty;
dr["Col5"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();
}
The important thing to note in the above code is the use of view state. The Viewstate
has been kept to facilitate the dynamic addition and deletion of rows
fucntionality. Since we need to preserve the data of rows other than row
being added or deleted we need some place to keep this data. We choose
view state for that. Now whenever the user choose to add a new row we need to do 2 things, first we need to add the new row in the grid and secondly we need to set the data entered in the already added rows.
So to add a new row to the gridview
private void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBox TextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBox TextBoxAddress =
(TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonList RBLGender =
(RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownList DrpQualification =
(DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grvStudentDetails.DataSource = dtCurrentTable;
grvStudentDetails.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
And to set the previoduly entered dataprivate void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox TextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBox TextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBox TextBoxAddress = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonList RBLGender = (RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownList DrpQualification = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
TextBoxName.Text = dt.Rows[i]["Col1"].ToString();
TextBoxAge.Text = dt.Rows[i]["Col2"].ToString();
TextBoxAddress.Text = dt.Rows[i]["Col3"].ToString();
RBLGender.SelectedValue = dt.Rows[i]["Col4"].ToString();
DrpQualification.SelectedValue = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
Now the similar stuff needs to be done when the user will choose to
delete the row. We need to delete the row user selected and then we need
to set the data of previous rowsTo delete the row selected
protected void grvStudentDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();
for (int i = 0; i < grvStudentDetails.Rows.Count - 1; i++)
{
grvStudentDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
And then to reset the data in other rowsprivate void SetRowData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxName = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
TextBox TextBoxAge = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
TextBox TextBoxAddress = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
RadioButtonList RBLGender = (RadioButtonList)grvStudentDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
DropDownList DrpQualification = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
//grvStudentDetails.DataSource = dtCurrentTable;
//grvStudentDetails.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//SetPreviousData();
}
Now when we run the application we can see that we can safely add and remove the rows dynamically to this Gridview
Note: The sample application is in full working condition. Running the application and debugging it(steping through it is highly advisable to understand the logic fully and get the jizt of whats happening inside
Friday, 18 January 2013
How to create and use User Control in asp.net
Here I show how to create and use user control in asp.net. In this simple example first I create a user control name ColorUserControl.ascx which shows a color ListBox. When someone select a color then the Label control show its name. Next I place this user control in a web form name Default.aspx. Here is the source code of both files.
ColorUserControl.ascx
- <%@ Control Language="C#" ClassName="ColoruserControl" %>
- <script runat="server">
- protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
- Label1.Text = "Your selected color: " +
- ListBox1.SelectedItem.Text.ToString();
- }
- </script>
- <asp:Label ID="Label1" runat="server" Font-Size="Medium" ForeColor="DeepPink"></asp:Label>
- <br /><br />
- <asp:Label ID="Label2" runat="server" Text="Choose Color" AssociatedControlID="ListBox1"></asp:Label>
- <asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true">
- <asp:ListItem>DarkSalmon</asp:ListItem>
- <asp:ListItem>DarkOliveGreen</asp:ListItem>
- <asp:ListItem>DarkMagenta</asp:ListItem>
- <asp:ListItem>DarkOrchid</asp:ListItem>
- <asp:ListItem>DarkSeaGreen</asp:ListItem>
- <asp:ListItem>DarkTurquoise</asp:ListItem>
- <asp:ListItem>DarkViolet</asp:ListItem>
- <asp:ListItem>DeepPink</asp:ListItem>
- </asp:ListBox>
Default.aspx
- <%@ Page Language="C#" %>
- <%@ Register Src="ColorUserControl.ascx" TagName="ColorUserControl" TagPrefix="uc1" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <script runat="server">
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>How to create and use User Control in asp.net</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h1>Page Top</h1>
- <hr />
- <h2>User Control</h2>
- <uc1:ColorUserControl ID="ColorUserControl1" runat="server" />
- <hr />
- <h3>Page Footer</h3>
- </div>
- </form>
- </body>
- </html>
GridView TemplateField OnClientClick event -using confirmation message for deleting records
RecordsDeleteConfirmationMessage.aspx
- <%@ Page Language="C#" AutoEventWireup="true" %>
- <%@ Import Namespace="System.Drawing" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <script runat="server">
- void SqlDataSource1_Deleted(object sender, SqlDataSourceStatusEventArgs e)
- {
- if (e.Exception == null)
- {
- if (e.AffectedRows == 1)
- {
- Label1.Text = "One Record deleted successfully!";
- Label1.ForeColor = Color.SeaGreen;
- }
- else
- {
- Label1.Text = "An error occured!";
- Label1.ForeColor = Color.DeepPink;
- }
- }
- else
- {
- Label1.Text = "Error Details: " + e.Exception.Message;
- }
- }
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head id="Head1" runat="server">
- <title>GridView TemplateField OnClientClick event -using confirmation message for deleting records</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h2 style="color:Navy; font-style:italic;">GridView Example: Using TemplateField OnClientClick Event</h2>
- <!-- Remove relation between Products and OrderDetails tables for test this example -->
- <asp:SqlDataSource
- ID="SqlDataSource1"
- runat="server"
- ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
- SelectCommand="Select ProductID, ProductName, QuantityPerUnit, UnitPrice From products"
- SelectCommandType="Text"
- DeleteCommand="Delete From Products Where ProductID=@original_ProductID"
- OldValuesParameterFormatString="original_{0}"
- OnDeleted="SqlDataSource1_Deleted"
- >
- <SelectParameters>
- <asp:Parameter Direction="Output" Name="Count" Type="Int32" />
- </SelectParameters>
- </asp:SqlDataSource>
- <asp:Label
- ID="Label1"
- runat="server"
- Font-Bold="true"
- Font-Size="Large"
- Font-Italic="true"
- ForeColor="SeaGreen"
- >
- </asp:Label>
- <br /><br />
- <asp:GridView
- ID="GridView1"
- runat="server"
- DataSourceID="SqlDataSource1"
- AutoGenerateColumns="false"
- AllowPaging="true"
- DataKeyNames="ProductID"
- PageSize="8"
- BorderColor="Salmon"
- AutoGenerateDeleteButton="false"
- Font-Names="Comic Sans MS"
- Width="850"
- >
- <HeaderStyle BackColor="Crimson" ForeColor="Snow" Height="45"/>
- <RowStyle BackColor="OrangeRed" ForeColor="Snow" Font-Italic="true" />
- <PagerStyle
- Height="45"
- HorizontalAlign="Right"
- BackColor="BurlyWood"
- Font-Bold="true"
- Font-Size="X-Large"
- ForeColor="Snow"
- BorderColor="RosyBrown"
- />
- <PagerSettings Mode="Numeric" />
- <Columns>
- <asp:TemplateField HeaderText="Delete">
- <ItemTemplate>
- <asp:Button
- ID="Button1"
- runat="server"
- Text="Delete"
- CommandName="Delete"
- OnClientClick="return confirm('Are you want to delete this record?')"
- Height="35"
- ForeColor="Crimson"
- Font-Bold="true"
- />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField HeaderText="Product ID" DataField="ProductID" />
- <asp:BoundField HeaderText="Product Name" DataField="ProductName" />
- <asp:BoundField HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" />
- <asp:BoundField HeaderText="Unit Price" DataField="UnitPrice"/>
- </Columns>
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
Subscribe to:
Posts (Atom)