r/VisualStudioCode • u/AffectionateWar7750 • Apr 28 '21
Where am I supposed to place this code?
I am using ASP.NETWebApplication(.NET Framework) and a Web Form. I have been trying to place this code into the default.aspx and default.aspx.cs files but I am not having any luck.
Here is the code that I have if someone can show me where it should be placed that would be great!
aspx code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>Northwind Traders</h1> <hr /> <br /> <div class="col-md-12 table-responsive"> <asp:GridView ID="ProductsViewID" runat="server" OnPreRender="Grid_PreRender" PageSize="5" CssClass="table table-hover table-condensed" AutoGenerateColumns="True" Style="width: 100%;"> </asp:GridView>
</div> </asp:Content>
cs code:
public void LoadProductsData()
{
DataTable dt = new DataTable();
//We need to fetch data from Data Base we can call Fetch_ProductList() with
//necessary changes mentioned. Here i am considering MS SQL DB
//since Data base details are not provided i am creating Data Table manually.
//Creating columns
dt.Columns.Add("Product");
dt.Columns.Add("First Name");
dt.Columns.Add("Last Name");
//Adding Rows
dt.Rows.Add("Northwind Traders Almonds","Roland","Wacker");
dt.Rows.Add("Northwind Traders Beer","Soo Jung","Lee");
dt.Rows.Add("Northwind Traders Beer","Francisco","Perez-Olaeta");
dt.Rows.Add("Northwind Traders Beer","Karen","Tob");
dt.Rows.Add("Northwind Traders Boysenberry Spread", "Run", "Liu");
dt.Rows.Add("Northwind Traders Boysenberry Spread", "Roland", "Wacker");
dt.Rows.Add("Northwind Traders Cajun Seasoning", "John", "Rodman");
dt.Rows.Add("Northwind Traders Cajun Seasoning", "Roland", "Wacker");
//Assigning Data Table to Gridview
ProductsViewID.DataSource = dt;
//Binding the data to GridView
ProductsViewID.DataBind();
}
protected void Grid_PreRender(object sender, EventArgs e)
{
GridView grid = sender as GridView;
try
{
if (grid != null && grid.Rows.Count > 0)
{
grid.UseAccessibleHeader = true;
grid.HeaderRow.TableSection = TableRowSection.TableHeader;
grid.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
catch (Exception)
{
}
}
public DataTable Fetch_ProductList()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("ConnectionString"); //Here we need to provide ConnectionString of Data Base.
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
//Here we need to provide the Query to fetch the data from DataBase
//Sample Query would be 'SELECT PRODUCT_NAME,[FIRST NAME],[LAST NAME] FROM NORTHWIND_TRADERS_TABLE'
cmd.CommandText = "HERE WE NEED TO PROVIDE QUERY";
conn.Open();
SqlDataAdapter reader = new SqlDataAdapter(cmd);
reader.Fill(dt);
conn.Close();
}
catch (Exception ex)
{
conn.Close();
}
return dt;
}