asp.net data entry form - asp.net

I want to build a form where users can enter some data in a few text boxes and click the "Add" button and have the the data appear in a grid or something like it. They need to be able to enter multiple rows.
Then when they are done they can click the "Save" button to save the data to the database.
How do I get the data from from the text boxes into the "grid"?
EDIT
Here's what I have so far
protected void Page_Load(object sender, EventArgs e)
{
DataTable myDataTable = new DataTable();
DataColumn dc1 = new DataColumn("Employee");
myDataTable.Columns.Add(dc1);
DataColumn dc2 = new DataColumn("Category");
myDataTable.Columns.Add(dc2);
DataColumn dc3 = new DataColumn("Description");
myDataTable.Columns.Add(dc3);
DataColumn dc4 = new DataColumn("P/S/N");
myDataTable.Columns.Add(dc4);
DataColumn dc5 = new DataColumn("Hours");
myDataTable.Columns.Add(dc5);
DataColumn dc6 = new DataColumn("WeekEnding");
myDataTable.Columns.Add(dc6);
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
DataRow row = myDataTable.NewRow();// i'm getting error here sayind myDataTable does not exist
row["Employee"] = LoginName1.ToString();
row["Category"] = ddlCategory.SelectedValue;
row["Description"] = txtDescription.Text;
row["P/S/N"] = ddlPSN.SelectedValue;
row["Hours"] = ddlHours.SelectedValue;
row["WeekEnding"] = txtWeekEnding.Text;
myDataTable.Rows.Add(row);

Ok your first problem from your comment:
i'm getting error here sayind myDataTable does not exist
Is because you defined your table in the Page_Load and then it goes out of scope at the end of the function. It sounds like you don't understand the basic concepts of ASP.NET and what you are trying to do.
Here is a quick and dirty untested solution to your problem but I must stress that you should try and understand why this solution works before trying to extend it or do more in ASP.NET. I hope my 10 minutes of my time helps you get a good start into understanding C# and ASP.NET.
[Serializable]
public class YourData
{
public string Employee { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string P_S_N { get; set; }
public string Hours { get; set; }
public string WeekEnding { get; set; }
}
// Used to add your list of data to the viewstate cache
// (There are other ways to store data between posts but I am trying to keep it simple)
public void SetYourCachedData(List<YourData> data)
{
ViewState["YourDataCache"] = data;
}
// Used to get your save data so far
public List<YourData> GetYourCachedData()
{
return ViewState["YourDataCache"] == null ?
new List<YourData>() : (List<YourData>)(ViewState["YourDataCache"]);
}
protected void Page_Load(object sender, EventArgs e)
{
// Do nothing
}
protected void btnAddToGrid_Click(object sender, EventArgs e)
{
// Get the data and store it in the ViewState to cache it between post backs
// Assuming one record added with each click.
List<YourData> data = GetYourCachedData();
data.Add(new YourData()
{
Employee = LoginName1.ToString(),
Category = ddlCategory.SelectedValue,
Description = txtDescription.Text,
P_S_N = ddlPSN.SelectedValue,
Hours = ddlHours.SelectedValue,
WeekEnding = txtWeekEnding.Text
});
// You can bind to any type of collection easily.
// You don't need to use a DataTable with a GridView
yourGrid.DataSource = data;
yourGrid.DataBind();
SetYourCachedData(data);
}
protected void btnSaveData_Click(object sender, EventArgs e)
{
// Pull data from the ViewState cache
List<YourData> data = GetYourCachedData();
// Now iterate through data to save it to your database...
// look this up if you don't know how as this is a lot more work.
}

looks like you just need to set the output object's datasource and bind it.
I.e.:
myGrid.datasource = myDataTable
myGrid.databind()
And as Kelsey says -- keep your datatable in scope.
a public dim right above your page_load would be easier, if you just want to try it out. Otherwise, the separate class approach is a good way to go.

Related

display next page asynchronously and then run its page load event

I have an airline site in which i am trying to display the fare from different API/Web service. But Firstly i want to display the search page--> Display processing --> binding data in the page from theses API/web service as they received.
but i am not able to display search page before the result processing.
What i have tried (code)-
public partial class asyncgridview : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
}
}
private string _Callback;
public string GetCallbackResult()
{
return _Callback;
}
public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = fetchData();
gvAsync.DataSource = table;
gvAsync.DataBind();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}
}
regards
Avishek

How to declare public variable from protected method in asp net?

I have database with images in folder on my server. To display this images I'am using DataList control. ItemTemplate include also a LinkButton
<asp:LinkButton ID="wybierzZdjecieBtn" OnClick="choosePhotoButton_Click" CommandArgument='<%#Eval("PhotoLinkAddress")%>' CssClass="wybierzZdjecieButton" runat="server">Choose photo</asp:LinkButton>
To receiving Value from LinkButton CommandArgument i'am using this method:
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
Response.Write(PhotoLinkAddressVar);
}
This works fine, no problems. But this is not what I want achieve. My intentions is send this variable "PhotoLinkAddressVar" to this method:
protected void addNewNews_Click(object sender, EventArgs e)
{
string trescStatus = "czeka";
string autor = Session["userName"].ToString();
DateTime data = DateTime.Now;
string dataFormat = "";
dataFormat = data.ToString("dd/MM/yyyy H:mm");
string CS = ConfigurationManager.ConnectionStrings["wiadomosciConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
string dodaj = "Insert into News (TytulNews, TrescNews, Autor, Data, Kategoria, Dotyczy, PhotoLinkAddress, Status) values (#TytulNews, #TrescNews, #Autor, #Data, #Kategoria, #Dotyczy, #PhotoLinkAddress, #Status)";
SqlCommand com = new SqlCommand(dodaj, con);
com.Parameters.AddWithValue("#TytulNews", tytulNewsTextBox.Text);
com.Parameters.AddWithValue("#TrescNews", trescTextBox.Text);
com.Parameters.AddWithValue("#Autor", autor);
com.Parameters.AddWithValue("#Data", dataFormat);
com.Parameters.AddWithValue("#Kategoria", kategoria.SelectedValue.ToString());
com.Parameters.AddWithValue("#Dotyczy", dotyczy.SelectedValue.ToString());
com.Parameters.AddWithValue("#PhotoLinkAddress", photoLinkAddressVar);
com.Parameters.AddWithValue("#Status", trescStatus);
com.ExecuteNonQuery();
}
}
User have to choose photo before press "Add News", because if He doesn't do that, he will receive error message. I dont know, how do that. I Was trying declare some kind public variable before PageLoad and do something like this:
protected void choosePhotoButtonButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
photoLinkAddressVar = button.CommandArgument.ToString();
}
but that method won't declare the variable. Do You have any idea, how can I achieve that ?.
You could use also the ViewState.
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
View["photoLinkAddressVar"]=photoLinkAddressVar;
Response.Write(PhotoLinkAddressVar);
}
Then in the addNewNews_Click method, you coukld retrieve this value with the following way:
com.Parameters.AddWithValue("#PhotoLinkAddress", ViewState["photoLinkAddressVar"]);
For further documantation about ViewState please look here.

passing gridview particular row datas to another page in asp.net?

i want to set session in login page and want to pass one page girdview data to another page.
slno title author publication takenby
1 book1 author1 pub1 sendrequest (button)
Above image showing gridview. when i click the Request Book button(1st one). it will redirect to sendrequest.aspx page. and have to bring that row data (i.e)
slno=1
title=book1
Author=author1
publication=publ
i tried below code
user.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string user = (string)(Session["User"]);
if (e.CommandName.Equals("SendRequestCmd"))
{
if (user == null)
{
Session["slno"] = null;
Session["bookname"] = null;
var clickedRow = ((Button)e.CommandSource).NamingContainer as GridViewRow;
// now access the cells like this
SlNo = clickedRow.Cells[0].Text;
Session["slno"] = SlNo.ToString();
BookName = clickedRow.Cells[1].Text;
Session["bookname"] = BookName.ToString();
}
}
}
sendquest.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string slno = "", bookname = "";
slno = (string)(Session["slno"]);
bookname = (string)(Session["bookname"]);
if (slno == null || bookname == null)
{
Response.Write("serial no: " + slno + "\nbookname: " + bookname);
}
}
protected void Logout()
{
Session.Clear();
}
but i got error in
slno=(string)(Session["slno"]);
bookname=(string)(Session["bookname"]);
why? anybody correct it?
else say better way?
Without posting your error it's difficult to see what the problem is. You could check that Sessions are enabled in your application.
Another way to do this (which may be better) is passing just the id/slno (via QueryString) to your other page, then perform a lookup to get your data at that stage.
I will surely create a type(Class) for booking
with slno title author publication properties and
public class Booking
{
public Booking()
{
//
// TODO: Add constructor logic here
//
}
public int slno { get; set; }
public string Title { get; set; }
public string author { get; set; }
public string publication { get; set; }
}
set all properties of object of booking type and pass that object in session
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string user = (string)(Session["User"]);
if (e.CommandName.Equals("SendRequestCmd"))
{
if (user == null)
{
Booking b = new Booking();
b.slno = clickedRow.Cells[0].Text;
b.Title = BookName.ToString();
Session["Booing"] = b;
}
}
}
and on receiving end just case that session value into that object again
and access each property just by using dot with object name .
Booking b=(Booking)Session["Booking"]
int slno=b.slno;
string Title=b.Title;
Without posting error not possible to give suggestion or correction , my answer is just how can you pass multiple values using session from one page to another .
Thanks

loading data in gridview is slow

For having the result like below and showing column 2 (user control) & column 3 (user control) grouped by column 1. I have made the code like below but it is slow , actually when I use just column 1 , loading is quick (5 seconds) , when I use column 1 & column2 (user control "document list") loading is 10 seconds, and when I use column 1 & column 2 (document list") & column3 ("DocTransList") loading is 45 seconds. I think my code in LINQ is not efficient , but I do not know how to solve it.
TRANSMITTAL No Documents REV
TT-001 DOC-001 01
DOC-002 01
public partial class Transmittals : System.Web.UI.Page
{
class TransmittalPresentationModel
{
public int TransID { get; set; }
public String TransmittalNo { get; set; }
public IEnumerable<tblDocument> Documents { get; set; }
public IEnumerable<tblTransmittall> DocTrans { get; set; }
}
private EDMSDataContext _DataContext;
protected void Page_Load(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
if (!IsPostBack)
{
DisplayAuthors();
}
}
private void DisplayAuthors()
{
var query =
from transmittal in _DataContext.tbltransmittalNos
orderby transmittal.TRANSMITTAL
select new TransmittalPresentationModel
{
TransID = transmittal.TransID,
TransmittalNo = transmittal.TRANSMITTAL,
Documents = transmittal.tblTransmittalls.Select(Transmittals => Transmittals.tblDocument),
DocTrans = transmittal.tblTransmittalls
};
GridViewTransmittals.DataSource = query.ToList();
GridViewTransmittals.DataBind();
}
protected void GridViewTransmittals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null) return;
TransmittalPresentationModel transmittal = (TransmittalPresentationModel)e.Row.DataItem;
DocumentList documentList = (DocumentList)e.Row.FindControl("DocumentList1");
DocTransList doctranslist = (DocTransList)e.Row.FindControl("DocTransList2");
documentList.Documents = transmittal.Documents;
documentList.DataBind();
doctranslist.DocTrans = transmittal.DocTrans;
doctranslist.DataBind();
}
}
Your having issues because your records all need to load into the GridView on each page load / refresh. This pulls from the database and draws each row each time which is time consuming.
Better options are to use Ajax to load your GridView.
Or use Paging on the server side and only give the data to your page it needs.

how to insert data within a calendar cell into a database

i have a calender and i was able to add text-box inside the cell using the day-render event but what i am trying to do is allow the user to add data to the text-box and then press add and the content is added to a database and showed inside that same text-box:
here is what i did:
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDate = DateTime.Now;
}
protected void update(object sender, DayRenderEventArgs e)
{
TextBox tb = new TextBox();
Button1.click += new EventHandler(insert);
e.Cell.Controls.Add(Button1);
e.Cell.Controls.Add(textBox2);
}
protected void insert(object sender, EventArgs e)
{
}
and i know how to insert the data but i am lost on how to identify it and output it back to the same text box
thanks
Well I'm not sure exactly what part you are lost on based on your question, so short of providing a complete working example I'll hit some of the main points:
1) To identify the data you are inserting, attach a date (and time if applicable) to the record. (Edit: are you looking for a mechanism to accomplish this? If so post your current DayRender handler code and Calendar markup).
2) To populate individual day data in a calendar, use Calendar.VisibleDate (to filter DB results) in a Page.Load handler to load a data structure (such as a List<T>) with day data for the entire month. Then in a Calendar.DayRender handler, add appropriate records from the structure to the e.Cell.
3) To cause the new results to show up on the first page refresh after insertion, you should be able to get away with using a Response.Redirect to the current page after insertion. This will cause the page generation process to restart, but you will lose ViewState.
Edit: Here is a basic prototype of what I tried to describe above. Note that you could pre-fetch into any enumerable data type, I use a List<T> here.
//Page code-behind
public partial class Default2 : System.Web.UI.Page
{
List<DataObject> liCurrentMonth = new List<DataObject>();
protected void Page_Load(object sender, EventArgs e)
{
liCurrentMonth = DataObject.GetCurrentMonth(Calendar1.VisibleDate);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
foreach (DataObject item in liCurrentMonth)
{
if (item.date == e.Day.Date)
{
Literal lit = new Literal();
lit.Text = item.text;
e.Cell.Controls.Add(lit);
}
}
}
}
//Data layer object
public class DataObject
{
public DateTime date { get; set; }
public string text { get; set; }
public static List<DataObject> GetCurrentMonth(DateTime currentdate)
{
//Get items from the db here, based on currentdate parameter
//and populate the List<DataObject>.
return new List<DataObject>();
}
}
I'm not sure you'll get this to work. Its the page viewstate that remembers the value entered into textboxes etc. Viewstate is created just before the page renders. The Calendar DayRender event is called during the calendars rendering, and hence after viewstate has done its thing. Therefore the viewstate mechanism is not aware of the existance of the textboxes and so will not track their content.
Perhaps you could assign each textbox an ID based on the month and day number, on postback you could check for this control ID in the Request.Form collection and do something with the data?

Resources