I have a repeater I want to add a title to in the HeaderTemplate from my database
This is my code so far
<asp:Repeater ID="topicView" runat="server">
<HeaderTemplate>
<tr>
<td>
<h1><%#DataBinder.Eval(Container.DataItem, "TopicName")%></h1>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "PostBody")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td>
</td>
</tr>
</FooterTemplate>
</asp:Repeater>
But nothing is displaying in my header. I heard that you can't use databinder in the header, so could anyone recommend how to do this?
this is my CS code
string topic = Request.QueryString["topicid"].ToString();
// Define the select statement.
// All information is needed
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='" + topic + "'";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
You don't need to bind to the data source, just bind to a simple property of the page. Use this in the HeaderTemplate:
<h1><%# TopicName %></h1>
Then add TopicName as a public property to the code-behind.
public string TopicName { get; set; }
Then set it when you run the query:
TopicName = Request.QueryString["topicid"].ToString();
Side Note
Not sure if you're aware, but you should be careful of SQL injection. Instead of injecting the query string directly into your SQL query, it's a good idea to use
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='{0}';
Then add the topic to your SqlCommand as a parameter.
Related
I'm fairly new to asp.net and c#, i've connected to a SQL database and now i'd like to show the data i have into a table.
This is my back-end:
public string getWhileLoopData()
{
string htmlStr = "";
SqlConnection conn = new SqlConnection("Data Source = secret;Initial Catalog = GTI;Persist Security Info = True;Integrated Security = true;User ID = user;Password = pass;");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [CORE_SYS_STATUS]", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int ID = reader.GetInt32(0);
int SYSTEM_NAME = reader.GetInt32(0);
int SYSTEM_STATUS = reader.GetInt32(0);
int SYSTEM_SHORTMSG = reader.GetInt32(0);
htmlStr += "<tr><td>" + ID + "<tr><td>" + SYSTEM_NAME + "<tr><td>" + SYSTEM_STATUS + "<tr><td>" + SYSTEM_SHORTMSG;
}
conn.Close();
return htmlStr;
}
This is my front-end:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ContentPlaceHolder">
<div class="bg-light text-center bg-light rounded border border-dark m-4">
<div class="col-md-12">
<h1 class="display-4 text-center p-4">Gestão de Alertas</h1>
<table class="table table-bordered table-hover text-center p-4 border border-dark">
<thead>
<tr class="table-success disabled">
<th style="width: 5%" scope="col">ID</th>
<th style="width: 20%" scope="col">Nome</th>
<th style="width: 15%" scope="col">Status</th>
<th style="width: 45%" scope="col">Mensagem</th>
</tr>
</thead>
<tbody>
<!-- I want to insert data here -->
</tbody>
</table>
</div>
</div>
</asp:Content>
And this is the result:
Result
It may look really silly and easy but i'm very new to this of programming, if anyone could help me figure out how to insert my data into the table i'd be very glad. Thank you!
There are many ways to achieve this.
I would recommend to take a look in the docs regarding to DataBinding, e.g.:
Retrieving data in aspnet web-forms
GridView DataBind (look at the sample there)
Furthermore you should take a look at the documentation regarding GetInt32:
GetInt32 MSDN
The parameter is the index of the column in the select statement and you are always passing 0 and that is certainly not what you want. I'd also recommend to explicitly name the columns you want in the select statement instead of using select *.
For a quick solution you could replace <%=getWhileLoopData()%> with an <asp:Literal /> control; in your code-behind, set it's Text property to (getWhileLoopData).
If you're new to ASP.NET, learning WebForms data binding will take a while as it's got some rules and peculiarities you need to get to grips with. To be honest unless you have to build this thing in WebForms you should start learning ASP.NET MVC, WebForms is a dead technology.
<% HtmlString str = new HtmlString(getWhileLoopData()); %>
<%= str %>
I am developing an asp.net page with two DropDown List populating values from the same table in the Database where a user is required to select account name and I would like the second DropDown List to automatically populates it's own values (Acount Code) sharing the same Account name based on the First dropdown list selection. Here is my sample code ...
<span class="label">
<asp:Label ID="Label2" runat="server" Text="Account Name"</asp:Label>
</span>
<asp:DropDownList ID="name" runat="server"></asp:DropDownList><br />
<span class="label">
<asp:Label ID="Label3" runat="server" Text="Account Code"></asp:Label>
</span>
<asp:DropDownList ID="code" runat="server"></asp:DropDownList>
and my C# code is as follow ..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand comm = new SqlCommand("SELECT AccountName, AccountCode FROM Account", conn);
conn.Open();
name.DataSource = comm.ExecuteReader();
name.DataTextField = "AccountName";
name.DataValueField = "AccountName";
name.DataBind();
conn.Close();
if(name.Text != null)
{
conn.Open();
SqlCommand com = new SqlCommand("SELECT AccountCode FROM Account WHERE AccountName= '" + name.Text +"'", conn);
code.DataSource = com.ExecuteReader();
code.DataTextField = "AccountCode ";
code.DataValueField = "AccountCode ";
code.DataBind();
}
}
}
}
In my case if i Change the Values of Account Name, the Account Code does not change automatically. How can i make that happen ..? Thank you
to meet your requirements you will have to add two attributes to your first drop down (1) "AutoPostBack" and (2) "OnSelectedIndexChanged".
1) Autopostback will cause a postback when you select an item in the dropdown.
2) OnSelectedIndexChanged is an event you will have to code to fill the second dropdown.
<asp:DropDownList ID="name" runat="server" AutoPostBack="true" OnSelectedIndexChanged="name_SelectedIndexChanged"></asp:DropDownList>
I'm starting in ASP.NET. I need to write data from two tables that are linked via ID. I would like to write in the cycle.
Example: I have a table States and Cities table:
1.United states
a. New York
b. Washington
c. Los Angeles
d. Chicago
e. Houston
2. Russia
a. Moscow
b. St. Petersburg
c. Omsk
d. Kazan
3. France
a. Paris
b. Lyon
c. Marseille
In PHP I solve this problem as follows
`
// cycle cities
$sql = mssql_query("SELECT * FROM States");
while($row = mssql_fetch_assoc($sql))
{
$id_state = row['ID_State'];
echo ($ row ['Name_State']);
// cycle city with id state
$sql_city = mssql_query("SELECT * FROM City WHERE ID_State = '. $id_state.'");
while ($row_city = mssql_fetch_assoc($sql_city))
{
echo($row['Name_city']);
}
}
Alternatively, just advice on how the operation is called, I do not know how to properly ask this in search
I tried Repeater in repeater but i have problem withI tried repeater in repeater, but I have a problem with passing parameters given line
Repeater in Repeater
I tried also in DataReader DataReader, but this is an open DataReader reports an error.
C# MySQL second DataReader in DataReader while loop
I also tried a treeview, but I am in the city must have a name and the name of the State, the same "name" and "name" which I can not have this.
Treeview validation
I now tried good code
select.aspx.cs
SqlDataAdapter cmd1 = new SqlDataAdapter("SELECT * FROM V_Dic", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "Dic");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from T_Obdobi", cnn);
cmd2.Fill(ds, "Obdobi");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select * from V_AktualizaceDic", cnn);
cmd3.Fill(ds, "OsCislo");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("Obdobi",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["Obdobi"].Columns["ID_Dic"]);
//ds.Relations.add
ds.Relations.Add("OsCislo",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["OsCislo"].Columns["ID_Dic"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["Dic"];
Page.DataBind();
select.aspx
<asp:Repeater ID="parentRepeater" runat="server">
<ItemTemplate>
<div class="accordion">
<div class="hlavni">
<%# DataBinder.Eval(Container.DataItem,"Dic") %>
</div>
<div class="rozbalovany">
<table>
<tr>
<td>Osobní číslo: </td>
<td><%# DataBinder.Eval(Container.DataItem,"OsCislo") %></td>
</tr>
<tr>
<td>Šetřené zdaňovací období: </td>
<td>
<div class="box2">
<!-- start child repeater -->
<asp:Repeater ID="childRepeater" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("Obdobi") %>'
runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"Obdobi\"]")%><br />
</ItemTemplate>
</asp:Repeater>
</div>
</td>
</tr>
</table>
<h3>Aktualizace:</h3>
<!-- end child repeater -->
<div class="box">
<table class="aktualizace" style="border: 1px solid #e9e9e9">
<tr>
<td><strong>Osobní číslo</strong></td>
<td>Jméno a Příjmení</td>
<td>Datum Aktualizace</td>
<td>Poznámka</td>
<td>Šetřené zdaňovací období</td>
<td>Změna Řešitele</td>
<td>Změna Plné moci</td>
<td>Záznam v Insolvenčním řejstříku</td>
<td>Významná změna s vazbou na data v OR</td>
<td>Jiná významná změna</td>
</tr>
<asp:Repeater ID="childRepeater2" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).Row.GetChildRows("OsCislo") %>'
runat="server">
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "[\"OsCislo\"]")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
but, I can't add parameter to first select. I tried
cmd1.SelectCommand.Parameters.Add("#EvCislo", SqlDbType.NVarChar, 50, "EvCislo");
but program have error message "this constraint cannot be enabled as not all values have corresponding parent values."
this example i see here
You can use JOINS for fetch data from two tables using ID like
SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id = table2.id WHERE table1.id = '1';
I have answer, add "false" behin relations
SqlDataAdapter cmd1 = new SqlDataAdapter("SELECT * FROM V_Dic", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "Dic");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from T_Obdobi", cnn);
cmd2.Fill(ds, "Obdobi");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select * from V_AktualizaceDic", cnn);
cmd3.Fill(ds, "OsCislo");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("Obdobi",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["Obdobi"].Columns["ID_Dic"], false);
//ds.Relations.add
ds.Relations.Add("OsCislo",
ds.Tables["Dic"].Columns["ID_Dic"],
ds.Tables["OsCislo"].Columns["ID_Dic"], false);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["Dic"];
Page.DataBind();
So I am porting a legacy application over from coldfusion to asp.net/c#. My problem is, (and I have searched all over for it, but I may not be wording my problem properly to get good results), is that I want to take my results from a the first query I have, and perform a second query to fill in that column.
Here's how I did it in coldfusion:
<cfquery name="p" datasource="db">
select * from table
</cfquery>
<cfloop query="p">
<tr>
<td>
#p.title#
</td>
<td">
#p.category#
</td>
<td>
#CreateObject("component","/components.dao").getuser(p.userid).user_fullname()#
</td>
</tr>
</cfloop>
You'll notice I call a component and method that I send the userid from the query too. This method has another query that calls a seperate database, and returns information on that user, in this case the full name rather than just the userid. This is where I am having problems in asp.net/c# for that I have created the following code:
<asp:Repeater id="program_list" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Eval("title") %>
</td>
<td>
<%# Eval("category") %>
</td>
<td>
<%# Eval("userid")%> (needs full name convert)
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
and in the codebehind
protected void Page_Load(object sender, EventArgs e)
{
try
{
DbConnection connection = new SqlConnection();
connection.ConnectionString = "***";
connection.Open();
SqlCommand cmd = (SqlCommand)connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table";
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
program_list.DataSource = reader;
program_list.DataBind();
reader.Close();
connection.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
As you can see, it only does the first part, outputting the original query, but I am not sure how to interact with that query in order to call the database the second time for the users details. Any ideas would be greatly appreciated, thanks.
so you need to call an sql query each line of repeater. you should use ItemDataBoundEvent , in this event you can have processing rows user_id and can make another query.
for example
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataRowView drw = (DataRowView)e.Item.DataItem
String sql = String.Format("Select * FROM UserInfo WHERE user_id={0}", drw["user_id"]);
Label lblUserName = (Label) e.Item.FindControl("lblUserName");
lblUserName.Text = //WWhatever you get from query...
}
You are looking for a ItemDataBound event. You can do a query in that event and populate other controls.
Ok guys, so I am trying to bind data into a dropdown list from c#. I am getting a Null error when trying to enter the data into the DDL's. I am using this code for the front end.
<asp:Repeater ID="RepeaterHardDrives" runat="server">
<HeaderTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hidHardDrivesPackageDefaultID" runat="server" />
<asp:HiddenField ID="hidHardDrivesPackageDefaultPrice" runat="server" />
<span>
<asp:Label runat="server" ID="lbHardDiskPrice" Text="$00.00/mo"></asp:Label></span><label>Hard
Drive:</label><asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
</asp:DropDownList>
<asp:ImageButton runat="server" ID="ShowHarddriveInfo" ImageUrl="/_Images/server_configurator_helpbutton.png"
OnClick="lnkShowHarddriveInfo_OnClick" /></div>
</td>
<td align="right">
<asp:Label runat="server" ID="lbHardDrivesPrice" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
<br />
</FooterTemplate>
</asp:Repeater>
for the backend I am trying to load a dynamic number of Dropdown lists into the repeater then databind them all with the same data.
public void PopulateHardDrives(int intSupportedDrives)
{
PreloadHardDriveRepeater(intSupportedDrives);
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connstrname"].ConnectionString);
SqlCommand cmd = new SqlCommand("Prod_SelectIDNamePriceByCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CategoryCode", "Hard Drive");
DataTable dtHardDrives = new DataTable();
using (conn)
{
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dtHardDrives.Load(dr);
ViewState.Add("dtHardDrives", dtHardDrives);
}
foreach (RepeaterItem riHardDrive in RepeaterHardDrives.Items)
{
DropDownList ddHardDrives = (DropDownList)riHardDrive.FindControl("ddHardDrives");
ddHardDrives.DataSource = dtHardDrives;//program gives NULL exception error here(object not set to instance of object however it know the count of the rows it is supposed to be pulling)
ddHardDrives.DataValueField = "ProductItemID";
ddHardDrives.DataTextField = "ItemName";
ddHardDrives.DataBind();
Label lbHardDrive = (Label)riHardDrive.FindControl("lbHardDrivesPrice");
lbHardDrive.Text = String.Format("{0:c}", Convert.ToDecimal("0.00"));
if (riHardDrive.ItemIndex != 0) //We do not want to allow None to be selected on the main drive
{
ddHardDrives.Items.Insert(0, "None");
}
}
}
and last but not least the function to setup the dynamic amount of DDL's looks like this
private void PreloadHardDriveRepeater(int intSupportedDrives)
{
int[] intArrDisks = new int[intSupportedDrives];
for (int intDiskCount = 0; intDiskCount < intArrDisks.Length; intDiskCount++)
{
intArrDisks[intDiskCount] = intDiskCount;
}
RepeaterHardDrives.DataSource = intArrDisks;
RepeaterHardDrives.DataBind();
}
I am calling a list of populate functions in a !page.isPostBack if statement and the only one that is not getting the data is this one with the Drown Lists. It gets the number of Rows(18) from the database, but it it throwing a Null error(Object reference not set to an instance of an object.) I have seen quite a few people have been running into this error while googling the problem, however I could not find a solution that worked for me. The PreloadHardDriveRepeater function seems to work fine when run alone it loads the correct amount of DDL's onto the page.
Thanks ahead of time.
Your control is "ddHardDrive":
<asp:DropDownList ID="ddHardDrive" DataTextField="ItemName" DataValueField="ProductItemID" runat="server" CssClass="lidropdown">
and your code is looking for "ddHardDrives"
riHardDrive.FindControl("ddHardDrives");
This would be easy to notice if you debugged into the function and looked at your variable values right before the exception is thrown.