Introduction:
This article is helps to how to get values
from database in datatable formats using asp.net. Assign and get the viewstate values,
Button click events then we bind the gridview after postback.
Designing Page (Source view):
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to maintain Datatable in viewstate using ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnviewstates" OnClick="btnviewstate_Click" runat="server"
Text="Maintain
viewstate in Datatable" />
<asp:GridView ID="grvOutput" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
</form>
</body>
</html>
VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Not
Page.IsPostBack Then
Dim dtTemp As New DataTable
Dim con As New SqlConnection("server=192.168.1.100;uid=sa;pwd=sa123;database=asp_dotnet")
con.Open()
Dim cmd As New SqlCommand("SELECT b.name,a.subject,a.mark FROM
studentmarkdetails a JOIN studentdetails b ON b.id=a.id", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dtTemp)
con.Close()
ViewState("StudentInformation")
= dtTemp
End If
End Sub
Protected Sub btnviewstate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dtTemp As DataTable = ViewState("StudentInformation")
grvOutput.DataSource = dtTemp
grvOutput.DataBind()
End Sub
C#.NET:
protected void Page_Load(object sender, EventArgs
e)
{
if (!Page.IsPostBack)
{
DataTable dtTemp = new DataTable();
SqlConnection con = new
SqlConnection("server=192.168.1.100;uid=sa;pwd=sa123;database=asp_dotnet");
con.Open();
SqlCommand cmd = new
SqlCommand("SELECT
b.name,a.subject,a.mark FROM studentmarkdetails a JOIN studentdetails b ON
b.id=a.id", con);
SqlDataAdapter da =new
SqlDataAdapter(cmd);
da.Fill(dtTemp);
con.Close();
ViewState["StudentInformation"]
= dtTemp;
}
}
protected void btnviewstate_Click(object sender, EventArgs e)
{
DataTable dtTemp = (DataTable)
ViewState["StudentInformation"];
grvOutput.DataSource = dtTemp;
grvOutput.DataBind();
}
Demo:
0 comments:
Post a Comment