Hi Guys in this session we can discuss about the how to display the data (data from database), it was quite easy to get the data for that declare the sqlconnection, sqldatareader and sqlcommand. In sqlconnection declare the connection string. In sqlcommand we can declare the sql command, the sqlcommand execute by the help of sqldatareader.
Header file
Before going to that first declare the header file, because we can access the sql.
using System.Data.SqlClient;
Now we are going to example program to explain how to display the data from database. For example we have country table in that country short name and full name there, if u click the short name in dropdownlist box the corresponding full will be appear in the another label
Coding in Design Page
<asp:DropDownList ID=”DropDownList1″ runat=”server” AutoPostBack=”True” DataSourceID=”SqlDataSource1″ DataTextField=”shortname” DataValueField=”shortname”></asp:DropDownList>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:signquickonline %>”SelectCommand=”SELECT [shortname], [fullname] FROM [countries]“></asp:SqlDataSource>
<asp:GridView ID=”GridView1″ runat=”server”></asp:GridView>
<asp:Label ID=”ldisplay” runat=”server” />;
In Code behind
SqlConnection mycn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["signquickonline"].ConnectionString);
SqlDataReader dataReader = null;
mycn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = (“SELECT [fullname] FROM [sign].[dbo].[countries] where [shortname]=’” + DropDownList1.SelectedValue.ToString() +”‘”);
cmd.Connection = mycn;
dataReader = cmd.ExecuteReader();
if (dataReader.HasRows) { while (dataReader.Read())
{
ldisplay.Text = dataReader["fullname"].ToString();
}
}
Place the coding in the page load event. here have the single output we can display in the label. Suppose we have multiple set of output what we can do? But still there is a chance declare the datalist or gridview in design page and access the datatable and datarow in the coding page.
Samplecoding
Add the gridview in design page
In Code behind
After execute the command(dataReader = cmd.ExecuteReader();)
Declare the datatable and datarow
DataTable objDT = new DataTable(“RVI”);
objDT.Columns.Add(new DataColumn(“name”, typeof(String)));
DataRow objDR;
if (dataReader.HasRows)
{
while (dataReader.Read())
{
objDR = objDT.NewRow();
objDR["name"] = dataReader["fullname"].ToString();
objDT.Rows.Add(objDR);
GridView1.DataSource = objDT.DefaultView;
GridView1.DataBind();
}
}
I hope you will enjoy this session.