This page is to retrieve data and display in the page and enable user to edit the info.
at this moment i need to retrieve the data and display it in textbox.
as i also have to retrieve multiple data from data and display on each different text box.
my .cs code is as follows:
foreach (DataRow dr in ChildImageDT.Rows)
{
myImage = new Images();
myImage.DateTaken = DateTime.Parse(dr["image_taken_dt"].ToString());
myImage.PlaceTaken = dr["image_taken_loc"].ToString();
myImage.DetailedInfo = dr["image_info"].ToString();
tableString += "<tr><td>Date Taken:</td>";
tableString += "<td><asp:TextBox ID=\"txtDateOfBirth\">" + myImage.DateTaken + "</asp:TextBox>";
tableString += "<asp:CalendarExtender ID=\"CalendarExtender1\" runat=\"server\" CssClass=\"AjaxCalendar\"";
tableString += "PopupButtonID=\"imgCalendar\" PopupPosition=\"Right\" TargetControlID=\"txtDateOfBirth\" Format=\"MM/dd/yyyy\"></asp:CalendarExtender>";
**tableString += "<asp:TextBoxWatermarkExtender ID=\"TextBoxWatermarkExtender1\" runat=\"server\" TargetControlID=\"txtDateOfBirth\" WatermarkText=\"Month/Day/Year\" WatermarkCssClass=\"watermarked\"></asp:TextBoxWatermarkExtender>";**
tableString += "<asp:Image ID=\"imgCalendar\" runat=\"server\" ImageUrl=\"img/Button/calendar.png\" Width=\"20px\" /></td>";
**tableString += "<td rowspan=3 ><input type=\"button\" class=\"right_content\" title=\"" + " " + "\"";
tableString += "onClick =\"location.href='ViewProfile.aspx?cid=" + "" + "'\" ";
tableString += "style=\"background-size:100%; background:url('/img/missing%20children%20pictures/";**
tableString += "" + ".jpg')\"/></td></tr>";
tableString += "<tr><td>Place Taken:</td>";
**tableString += "<td>" + textbox1.Text = myImage.PlaceTaken;**
tableString += "</td><td></td></tr>";
tableString += "<tr><td rowspan=3>Detailed Info:</td>";
tableString += "<td rowspan=3><input id=\"txtImageDetailedInfo\" type=\"text\">" + myImage.DetailedInfo + "</input></td><td></td></tr>";
tableString += "<tr><td><input id=\"SetProfilePicture\" type=\"radio\" /></td></tr>";
tableString += "<tr><td><input id=\"DeletePhoto\" type=\"checkbox\" /></td></tr>";
}
the page should look like this :
where each photo as it own description and i need to retrieve all the images and data from
What for you need this? I thing you have a bad design of you application and the best solution of your issue its to use another method do display your data and controls. As I understand you – you need to display many repeater blocks of data, wich include your textboxes. Try to read about Repeater Control. For example, your problem will have next solution:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>UserName:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Image:</td>
<td><asp:TextBox ID="txtPassword" Text="<%#Eval("Password")%>" runat="server" /></td>
</tr>
<tr>
<td>Image:</td>
<td><asp:Image ID="TextBox1" ImageUrl="<%#Eval("ImgUrl")%>" runat="server" /></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
And in code you can use your repeater like that:
public partial class _Default : System.Web.UI.Page
{
private class User
{
public string Name { get; set; }
public string Password { get; set; }
public string ImageUrl { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
var userList = new[] {
new User {Name = "user1", Password = "pass1", ImageUrl = "img1.jpg"},
new User {Name = "user2", Password = "pass2", ImageUrl = "img2.jpg"},
new User {Name = "user3", Password = "pass3", ImageUrl = "img3.jpg"},
};
Repeater1.DataSource = userList;
Repeater1.DataBind();
}
}
Mor about Repeater you can read here
You should use Repeater control or some other data repeater control for building such layouts.
I think you can author your code in better way. I suggest two ways:
You can use PlaceHolder control and add control to place holder. You can add the html via Literal Control.
LiteralControl lit = new LiteralControl("<tr><td>Date Taken:</td>");
placeHolder1.Controls.Add(lit);
[Code]
var txt = new TextBox();
txt.Text = [Data];
PlaceHolder1.Controls.Add(txt);
you can override the Render page event and write html by HTMLTextWriter.
protected override void Render(HtmlTextWriter output) {
output.Write ("<h3> Hello </h3>");
}
According your question:
i have tried this but could u guide me on how to use foreach (DataRow dr in ChildImageDT.Rows) with repeater.. i cant seem to get to populate out the data
Try to do next:
var userList = new List<User>();
foreach (DataRow row in dataTable.Rows)
{
var user = new User()
{
Name = row["Name"].ToString(),
Password = row["Password"].ToString(),
ImageUrl = row["ImageUrl"].ToString()
};
userList.Add(user);
}
repeater1.DataSource = userList;
repeater1.DataBind();
}
Of course, you need to define your class, that implement data contrcats, accordin your task.
And i strongly recommend you, spend one or two days to read chapter about Repeater. Believe me, if you do it - your progress of your create yuor program is much accelerated.
p.s.: try to ready about Linq - its very powerfull technology to replace your foreach in task, like this.
You need to build up the control tree properly. For example you need to instantiate a TextBox (TextBox txt = new TextBox()) and add it to the Controls collection of another control. For this type of thing I would define an asp:Panel in markup and add my dynamic controls in the code behind
Related
I need the user input to appear after the word 'assigned'. I tried:
$(document).ready(function()
{
$('#txtInstructions').keyup(function (e) {
var txtVal = $(this).val();
$('#StrautoDoc').val(txtVal);
});
});
but this was overwriting the current text I have generated via C#, which has information I am pulling from a database.
C# string I'm generating:
StrautoDoc.Text = DateTime.Now.ToString("MM/dd/yy") + " - " + GetUserName() + " assigned " + [user input for the task summary] + " to " [person being assigned the task];
This C# file is synced with a .aspx file where 'txtInstructions' (an
E.g.
private string GetTaskSummary()
{
tbltask currentTask = new tblTask();
currentTask.Instructions = txtInstructions.Text;
if (currentTask != string.Empty)
{
currentTask.Instructions = Convert.ToString(txtInstructions.Text);
}
return currentTask;
}
'tblTask' & 'Instructions' are from a db. But nothing seems to work, I was wondering what I am doing wrong, and what I can do to get this to work properly. Thanks in advance!
You need to rethink your whole approach. ASP.NET was created so that you do not have to work with HTML/JavaScript directly.
You can create the text boxes in your ASPX file as follows:
<asp:TextBox runat="server" ID="txtInstructions" OnTextChanged="txtInstructions_TextChanged" AutoPostBack="true" />
<asp:TextBox runat="server" ID="StrautoDoc" />
The in your code behind file, you can have the following:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtInstructions_TextChanged(object sender, EventArgs e)
{
StrautoDoc.Text = DateTime.Now.ToString("MM/dd/yy") + " - " + GetUserName() + " assigned " + txtInstructions.Text + " to [person being assigned the task]";
}
private string GetUserName()
{
return "name";
}
This works entirely in C# without you having to write any JavaScript as ASP.NET was intended. Is there any reason why you want to be using Jquery seeing that your entire problem can be solved in ASP.NET alone?
Hi it just so happens that I have to need this kind of approach (or any suggestion if you have)
this code produce table
while (rd.Read())
{
resultsHtml.Append("<tr class='odd gradeX'>");
resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
resultsHtml.Append("<td>" + rd["region_tag"].ToString() + "</td>");
resultsHtml.Append("<td class='center'>");
resultsHtml.Append("<div class='tooltip-demo'>");
resultsHtml.Append("<a class='btn btn-info' href='regionEdit.aspx?id=" + rd["region_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
resultsHtml.Append("<asp:Button ID='btnDelete' runat='server' Text='Login' CssClass='btn btn-outline btn-primary' Style='width: 100px;' OnClick='btnDelete_Click' />");
resultsHtml.Append("</div>");
resultsHtml.Append("</td>");
resultsHtml.Append("</tr>");
}
if you will notice there is an asp:button there. because i want that if the user clicks that button, it will just delete it. So I put an
public void btnSubmitDelete_Click(object sender, EventArgs e)
{
}
but the things is. It is not displaying and I can't figure out how to put the region_id in the asp:button to determine which is which to delete and every loop of the while. Please help
i think when u want to add an asp control and show that control to end user u should add dynamically control to a placeholder or panel like this code :
<asp:PlaceHolder runat="server" ID="_plchControles"></asp:PlaceHolder>
and in code bihind :
var btn = new System.Web.UI.WebControls.Button();
btn.Text = "sample";
btn.ID = "btnSubmitDelete";
btn.OnClientClick += btnSubmitDelete_Click;
_plchContent.Controls.Add(btn);
Your script will work as HTML control and you can bind click event from Javascript. To do so define a WebMethod in c# and call it from Javascript click event.
e.g.
$("#btnDelete").on("click",function(e)
{
var para=[]
para.param1=val1;
para.param2=val2;
$.post("/path/delete",para,function(result)
{
});
});
C#
[WebMethod]
public void delete(string param1,string param2)
{
//Delete code here
}
else
mohammadreza izadi answers will work if you want to asp.net control but you have to make object of button as defined not string.
my area of programming expertise isn't web programming however I'm currently expanding my knowledge by studying C#.net webforms and I am working on an example.
I have a button which has this code:
protected void Button1_Click(object sender, EventArgs e)
{
Course course = new Course(txtId.Text, txtName.Text, txtDesc.Text);
// This line checks to see if I already have a course manager
cm = (courseManager)Session["CourseManager"];
// If I do not have a course manager, it will create one for me.
if (cm == null)
{
cm = new courseManager();
}
// This will add a course to my list of courses
cm.addCourse(course);
// This will make sure that my web page can see the list of courses.
Session.Add("CourseManager", cm);
// This will reset my text boxes
txtId.Text = "";
txtName.Text = "";
txtDesc.Text = "";
// This will print course to page
//lblId.Text = course.getId();
//lblName.Text = course.getName();
//lblDesc.Text = course.getDesc();
}
and then on the webform I have this:
<table id="courses">
<%
if (cm != null)
{
for (int i = 0; i < cm.getCourses().Count(); i++)
{
string id = cm.getCourses().ElementAtOrDefault(i).getId();
string name = cm.getCourses().ElementAtOrDefault(i).getName();
string desc = cm.getCourses().ElementAtOrDefault(i).getDesc();
%>
<tr>
<td><%=id %></td>
<td><%=name %></td>
<td><%=desc %></td>
</tr>
<%
}
}
%>
</table>
I am told this is all I need to get an active session going however the session doesn't seem to be saving the courseManager class to the session and it keeps creating new instances of the coursemanager class. Am I missing something that c#.net webforms need to keep items in a session?
regards,
Joey
I have created link button using c# code but these are not click able why?
This is c# code
<% {
List<string> PMlist = new List<string>();
PMlist = PManifacutrerList;
foreach (string PM in PMlist)
{
Response.Write(PM);
}
}
%>
And following code is used to add list li in the PMlist
PMList.Add(
"<li><asp:LinkButton ID=\"LinkButton1\" style=\"color: Blue;font-family: Microsoft New Tai Lue; text-decoration: none;\" runat=\"server\">" +
ds.Tables[0].Rows[i]["PM_name"].ToString() + "</asp:LinkButton></li>");
Your Response.Write(PM) is simply writing HTML to the response output. If you really want to use a LinkButton, you need to create an instance:
LinkButton lb = new LinkButton();
lb.Text = "click me";
lb.Click += new EventHandler(delegate (object s, EventArgs ev) {
// handle click event
});
form1.Controls.Add(lb);
If you don't need a server post back, then you can just use a simple link such as:
PMList.Add(
"<li><a href='#' style='color: Blue;font-family: Microsoft New Tai Lue; text-decoration: none;'>" + ds.Tables[0].Rows[i]["PM_name"].ToString() + "</a></li>");
Hope it helps!
You need to write OnClick event
In order to dynamically add a control there must be a container.
If you don't have a container on page you can a placeholder
control & add controls to it
You must create an instance of control to add it onto page
Label myLabel = new Label();
myLabel.Text = "Sample Label";
myPlaceHolder.Controls.Add(myLabel);
Adding Controls dynamically:MSDN
Here's the thing, I now have a working prototype of what I want and it seems to work perfectly for what I want to do. With that said, this cannot POSSIBLY be the best way to do it. And by best I mean both in terms of program simplicity but also HOW i actually coded it. Anyways first a description of what the page should do:
1) the page contains a textbox (Textbox1), a placeholder (Placeholder1), and a button (Button1)
the code for this is simple:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<hr />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<hr />
2) the user can put a number into the textbox (lets say 99) and click the button. the placeholder will then be filled with 99 textboxes with a "save" button next to each one
3)the user can edit any textbox and click save next to it and the function that is then called by the button click event needs to be able to have access to A) the textboxes current value, B) the textboxes old value, C) any amount of meta data
here is my current working solution:
protected void Page_Load(object sender, EventArgs e)
{
createStuff(false);
}
void test(object sender, EventArgs e)
{
Button btn = (Button)sender;
Response.Write(btn.ID + "Clicked" + "<br />");
Response.Write("Metadata: " + Session[btn.ID + "a"] + "<br />");
Response.Write("Old text: " + Session[btn.ID + "b"] + "<br />");
TextBox txtBlah = (TextBox)PlaceHolder1.FindControl("txt"+btn.ID);
Response.Write("New text: " + txtBlah.Text + "<br />");
Session[btn.ID + "b"] = txtBlah.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["num"] = TextBox1.Text;
createStuff(true);
}
private void createStuff(bool btnClick)
{
PlaceHolder1.Controls.Clear();
int numBtn = Convert.ToInt32(Session["num"]);
for (int i = 0; i < numBtn; i++)
{
TextBox txtTemp = new TextBox();
txtTemp.Text = "old" + i;
txtTemp.ID = "txt" + "btn" + i;
PlaceHolder1.Controls.Add(txtTemp);
Button btn = new Button();
btn.Text = "btn" + i;
btn.ID = "btn" + i;
btn.Click += new EventHandler(test);
PlaceHolder1.Controls.Add(btn);
Session[btn.ID + "a"] = "meta" + i;
if (btnClick)
{
Session[btn.ID + "b"] = txtTemp.Text;
}
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
I think this is actually pretty decent and I am very happy with it. But, I know there have to be some improvements i can make since some of the tutorials on how the ASP postback system and object model or whatever its called are even now confusing me some.
any help or even just ideas are helpful thanks.
The only major improvement i can see is: use a UserControl, put the TextBox and Button inside, add properties (like OldValue/NewValue, stored in ViewState/TextBox) and add these UserControls to the PlaceHolder after you've created instances by using LoadControl.
The "MetaData" should also be stored as property in the UserControl. You should use Events to communicate between the UserControl and Page(f.e. TextSaved).
You can store the number of created controls in ViewState instead of the Session. That's the only thing you need to store in the Page. Append the index of the UserControl to it's ID.
General advantages of a Web User Control:
The biggest advantage of the Web User controls is that they can be created as a site template and used through out the site. For example they can be made to contain the Menu/Link structure of a site and can be used at all the other aspx pages.
This means the following :
If the website introduces a new site-wide link within the current layout/structure, it is enough if we put it on the user control once. All pages will be updated once if the web user control is used in them.
If there is any link to be corrected, it can be done once at the server side.
The .ascx files can either be used as a simple alternative to the plain HTML or they can also be used to respond to events: This means even custom code can be created against them and put in the code behind files.
http://www.dotnet-guide.com/usercontrol5.html
UserControls encapsulate complexity what is always good to increase
Reusability
Readability
Maintainability
Extensibility
... and to reduce the possibility of errors
Read this SO-answer for more examples.
ok i dunno if this is the right place for me to post back my newest code but i guess it would count as an "answer". also I want to say thank you so much for your answers they have been incredibly helpful. a little cryptic but fifty pages of tutorials or so later and yes your recomendations were fantastic so thank you and bravo. anyways heres my newest one that works perfectly with what I think are your recomended additions. if you want to take a peak and see if youd still do anything a little different or maybe in an easier way please feel free to let me know
first my user control "MyControl"
ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MyControl.ascx.cs" Inherits="DBtest.MyControl" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
ascx.cs:
//private String _oldText;
private String _metaData;
public String OldText
{
get
{
//return _oldText;
return (String)ViewState["OldText"];
}
set
{
//_oldText = value;
ViewState["OldText"] = value;
}
}
public String MetaData
{
get
{
return _metaData;
}
set
{
_metaData = value;
}
}
public String NewText
{
get
{
return TextBox1.Text;
}
set
{
TextBox1.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("My ID: " + this.ID + "<br />");
Response.Write("My Metadata: " + _metaData + "<br />");
Response.Write("My Old Text: " + ViewState["OldText"] + "<br />");
Response.Write("My New Text: " + TextBox1.Text + "<br />");
ViewState["OldText"] = TextBox1.Text;
}
then my page, aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TESTdynamicButton3.aspx.cs" Inherits="DBtest.TESTdynamicButton3" %>
<%# Register TagPrefix="uc" TagName="Spinner" Src="MyControl.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<hr />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<hr />
</asp:Content>
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
createStuff(false);
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["num"] = TextBox1.Text;
createStuff(true);
}
private void createStuff(bool btnClick)
{
PlaceHolder1.Controls.Clear();
int numBtn = Convert.ToInt32(ViewState["num"]);
for (int i = 0; i < numBtn; i++)
{
MyControl temp2 = LoadControl("MyControl.ascx") as MyControl;
temp2.ID = "uc" + i;
temp2.MetaData = "meta" + i;
//not sure why this DOES work, i would think it is overwritten each page load >.<
temp2.OldText = "old" + i;
if (btnClick)
{
temp2.NewText = "old" + i;
//not sure why this doesnt work below this line
//temp2.OldText = "old" + i;
}
//also not sure why this won't work
//temp2.OldText = temp2.NewText;
PlaceHolder1.Controls.Add(temp2);
}
}
and i also have a couple contents where im not sure it makes perfect sense why or do or dont use these lines to get the "old text" viewstate to populate properly initially. i would have thought i need to have that buttonclick check and only set the viewstate that first time to get it to work. also im not sure i understand why when i tried moving the createStuff() function to OnInit or the pre init functions overridden it wouldnt work..
thanks!
Leo