Intoduction:
This article is helps get distinct values from database in datatable formats using asp.net. Page load events bind the gridview before get distinct values. After bind the gridview distinct records of subject,mark columns also.
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>Distinct values in datatable n number of columns c# / vb.net using ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnDistinctValues" runat="server" OnClick="btnDistinctValues_Click"
Text="Distinct values in Datatable" />
Text="Distinct values in Datatable" />
<br />
<br />
<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
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")
SqlConnection("server=192.168.1.100;uid=sa;pwd=sa123;database=asp_dotnet")
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM studentmarkdetails", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dtTemp)
con.Close()
ViewState("StudentInformation") = dtTemp
grvOutput.DataSource = dtTemp
grvOutput.DataBind()
End If
End Sub
Protected Sub btnDistinctValues_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim dtTemp As DataTable = ViewState("StudentInformation")
Dim dtDistinctRecords As DataTable = dtTemp.DefaultView.ToTable(True, "subject","mark")
grvOutput.DataSource = dtDistinctRecords
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 * FROM studentmarkdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtTemp);
con.Close();
ViewState["StudentInformation"] = dtTemp;
grvOutput.DataSource = dtTemp;
grvOutput.DataBind();
}
}
protected void btnDistinctValues_Click(object sender, EventArgs e)
{
DataTable dtTemp = (DataTable)ViewState["StudentInformation"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "subject","mark");
grvOutput.DataSource = dtDistinctRecords;
grvOutput.DataBind();
}
Demo:
0 comments:
Post a Comment