Adding the row one by one in the button click..
(i tried but its overwirting the same row)
Here it is in vb for you. Tested it, seems to work fine. Declare dt as shared
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Shared dt As DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
dt = New DataTable
dt.Columns.Add("Colum1")
dt.Columns.Add("Colum2")
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
dt.Rows.Add(TextBox1.Text, TextBox2.Text)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
End Class
A gridview should be bound to a datasource. You'll need to add a record to this datasource and then call myGridView.Bind() to bind to it.
Lots of info on MSDN about GridViews:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.aspx
You can do something like this...
static DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("Colum1");
dt.Columns.Add("Colum2");
}
private void button1_Click(object sender, EventArgs e)
{
dt.Rows.Add(textBox1.Text, textBox2.Text);
dataGridView1.DataSource = dt;
}
Related
I'm trying to dynamically create a datatable that will allow me to populate single records multiple times when a procedure is executed. I know how to create the datatable with the columns I need but my problem is that every time I execute the sub routine to add a record it re-initializes the datatable and wipes out the previously populated record. How do I create the datatable so that it initializes only once? I've tried initializing during the Page_Load event with a 'Not IsPostback' condition but that doesn't work. Any other ideas?
Partial Public Class ContactLookup
Inherits System.Web.UI.Page
Dim dtContacts As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
dtContacts = New DataTable
dtContacts.Columns.Add("Email", GetType(String))
dtContacts.Columns.Add("AccountNum", GetType(String))
End If
End Sub
Protected Sub btnAddContact_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddContact.Click
Dim AcctNum As String = txtLocAcct.Text
Dim Email As String = txtEmail.Text
Dim drContacts As DataRow = dtContacts.NewRow
drContacts("Email") = Email
drContacts("AccountNum") = AcctNum
dtContacts.Rows.Add(drContacts)
End Sub
End Class
If I am correct than you need the table returned by the query as datatable. If its so then you can try this. Change your SqlCommand like this,
var dt =new DataTable(); // a new table to populate dynamically.
var reader = cmd.ExecuterReader(CommandBehaviour.SequentialAccess");
dt.Load(reader);
return dt; // now your dt will be query dependent.
Sorry the answer is in C#. You can convert it to VB at http://converter.telerik.com
Updated Answer
In your case i would suggest create a class instead of datatables and datacolumns. See a sample below:
public class Student
{
public string Name{get;set;}
public int Roll{get;set;}
}
In your code behind
private Student _stud = new Student();
private void FillObjects(){
_stud.Name= txtName.Text;
_stud.Roll=Convert.ToInt32(txtRoll.Text);
}
private void ButtonClick{
FillObjects();
YourClass.SaveMethod(_stud);
}
I have a search on a grid view which limits the results. I would like the grid view to repopulate with all entries if a. the search box is empty or b. the user hits a button to refresh.
Protected Sub btnSeach_Click(sender As Object, e As EventArgs) Handles btnSeach.Click
StaffDetailsStaffGridView.DataSourceID = ""
StaffDetailsStaffGridView.DataSource = ObjectDataSource1
StaffDetailsStaffGridView.DataBind()
If txtFnameSearch.text = " " Then
StaffDetailsStaffGridView.DataBind()
End If
End Sub
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
StaffDetailsStaffGridView.DataBind()
End Sub
End Class
StaffDetailsStaffGridView.DataBind() obviously doesn't work.
how do I do this properly?
The best way to repopulate the GridView is by having a method specifically for binding your data and calling when needed.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
BindGrid();
}
private void BindGrid()
{
StaffDetailsStaffGridView.DataSource = ObjectDataSource1;
StaffDetailsStaffGridView.DataBind();
}
protected void btnRefreshSearch_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void btnSeach_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtFnameSearch.text))
{
BindGrid();
}
}
I'm assuming you are filtering your data directly via the ObjectDataSource.
You should get the datasource again and set it as the DataSource and then bind again.
Something like this
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
Dim searchKey as String
searchKey =txtFnameSearch.Text.Trim()
Dim staffSearchREsults=MyService.GetSearchResults(searchKey)
StaffDetailsStaffGridView.DataSource = staffSearchREsults
StaffDetailsStaffGridView.DataBind()
End Sub
Assuming MyService.GetSearchResults method will return you a valid search result based on the search key.
This will not work because, after postback, gridview's datasource will be lost. So you always need to set datasource before DataBind() is called.
StaffDetailsStaffGridView.DataSource = ObjectDataSource1
StaffDetailsStaffGridView.DataBind()
You can also save ObjectDataSource1 into session and use it later for binding:
Session["MyObjectDataSource"] = ObjectDataSource1;
...
Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
StaffDetailsStaffGridView.DataSource = Session["MyObjectDataSource"]
StaffDetailsStaffGridView.DataBind()
End Sub
If you're using a declarative datasource, you can just call DataBind() again on the GridView:
StaffDetailsStaffGridView.DataBind()
I have problem with bubbleup event from my dynamic loaded ascx control (katalogbooklist.ascx) to it´s parent control (ViewAJBarnboksKatalog.ascx)
i need to fire/run sub uppdateraAndraModuler in the parent control when the event addMultiVotes_command fires in the chiled control.
is there any one who knows or have an idea on how to do this?
/
Andreas
(the code lives in a dotnetnuke cms modules, if that's any help)
Partial Class ViewAJBarnboksKatalog '<--------Partial codebehind file for ViewAJBarnboksKatalog.ascx
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
.. code for adding for loading katalogbooklist.ascx dynamic...
Me.Controls.Add(..code.. add katalogbooklist.ascx ..) '
End Sub
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim t As Execkoden = New Execkoden()
AddHandler t.onAjeventtest, AddressOf Uppdateramod
End Sub
Public Sub Uppdateramod(sender As Object, e As ajeventArgs)
uppdateraAndraModuler()
End Sub
Public Sub uppdateraAndraModuler()
'..do some code
End Sub
End Class
Partial Class katalogenBookList '<--------Partial codebehind file for katalogbooklist.ascx
Protected Sub addMultiVotes_command(ByVal sender As Object, ByVal e As System.EventArgs)
'..more code...
Dim te As New Execkoden ' <----- i want to use the constructor to raise the event in class Execkoden can´t raiseevent directly it wont´t fire
'... more code...
End sub
End Class
Public Class ajeventArgs : Inherits EventArgs
Public Sub New()
End Sub
End Class
Public Delegate Sub Uppdatera(sender As Object, e As ajeventArgs)
Public Class Execkoden
Public Event onAjeventtest As Uppdatera
Public Sub New()
RaiseEvent onAjeventtest(Me, New ajeventArgs)
End Sub
End Class
Create an event handler in the child control, like this:
public event EventHandler DeleteButtonClick;
When a button is clicked in the child control, do this:
protected void DeleteClick(object sender, EventArgs e)
{
if (this.DeleteButtonClick != null)
this.DeleteButtonClick(sender, e);
}
And in your parent control, in the markup:
<UC:SomeUserControl ID="UserControl1" runat="server" OnDeleteButtonClick="UserControl1_DeleteClick" ...>
And in the code behind of the parent control:
protected void UserControl1_DeleteClick(object sender, EventArgs e)
{
//do something
}
I would suggest using the IMC or Inter Module Communication feature that's built in to DotNetNuke.
I have the following code:
Imports System.Data
Partial Class Students_AddWishes Inherits System.Web.UI.Page
Public dt As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ID", System.Type.GetType("System.Int32"))
dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"))
dt.Columns.Add("major", System.Type.GetType("System.Int32"))
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim row1 As DataRow = dt.NewRow()
row1("ID") = dt.Rows.Count + 1
row1("univirsity") = ddlUnivs.SelectedValue
row1("major") = ddlMajors.SelectedValue
dt.Rows.Add(row1)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
End Class
The problem is it shows only one row or record. How to make it shows many records?
Your page load event you are not checking if it is a post back:
If Not IsPostBack Then
'process code if it is not a post back
End If
Everytime you click the btnAdd button your page does a post back to the server.
I just noticed that you probably are not understanding the life time of an object.
You had done this in your code:
Public dt As New DataTable
The problem with that is you have defined this is a class variable and once the page has loaded you have an instance of type dt that may have some columns associated with it. But as soon as you record an event such as a button click that reference is destroyed and a new dt is created.
You will have to make some use of session variables or a database to store the state of dt.
Here is an example in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"));
dt.Columns.Add("major", System.Type.GetType("System.Int32"));
Session["MyDataTable"] = dt;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["ID"] = t.Rows.Count + 1;
row1["univirsity"] = 3;
row1["major"] = 31;
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
And the same code in vb.net:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
Dim dt As New DataTable()
dt.Columns.Add("ID", System.Type.[GetType]("System.Int32"))
dt.Columns.Add("univirsity", System.Type.[GetType]("System.Int32"))
dt.Columns.Add("major", System.Type.[GetType]("System.Int32"))
Session("MyDataTable") = dt
End If
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim t As DataTable = DirectCast(Session("MyDataTable"), DataTable)
Dim row1 As DataRow = t.NewRow()
row1("ID") = t.Rows.Count + 1
row1("univirsity") = 3
row1("major") = 31
t.Rows.Add(row1)
Session("MyDataTable") = t
GridView1.DataSource = t
GridView1.DataBind()
End Sub
So now what the code does is instantiate a new datatable object as long as we are on the page (first post back) and adds the columns. Once it has defined the data table we throw it in some session state. When you click the add button you cannot in your previous code just keep using dt because dt scope was lost in your prior code. We do this by assigning the sessioned datatable which was stored prior to a temp datatable. We add the row and reset the session that way the next time we add a row it will display the second row, then third row, and so on...
I recommend a good asp.net book on such as Beginning ASP.net 3.5 in C# 2008. There are a ton of vb.net books on the same subject matter.
You need to save the datatable to Session, because local variables are not preserved. So you need to do:
protected override OnLoad(..) //or OnInit
{
dt = Session["DataTable"] as DataTable;
if (dt == null)
{
dt = new DataTable();
//load columns
}
}
protected override OnUnLoad(..)
{
Session["DataTable"] = dt;
}
Session saves the data table reference across postbacks as the web is stateless.
I am trying to aid another programmer with a page called Default.aspx with a code-behind section, and unfortunately I am at a bit of a loss.
Partial Class _Default
Inherits OverheadClass
'A bunch of global variables here'
Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
'Function goes here'
And in the OverheadClass we have
Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e as System.EventArgs) Handles MyClass.Load
The desired effect is when the OverheadClass is inherited, we want its load to run before the load event on the page runs. There is probably a very simple answer to this that I am missing.
Edit: I forgot to note that we write in VB, and not C# as many of you are used to for ASP.
You should be able to override the OnLoad and call the base class's OnLoad first, then your class, for example:
C# Version
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Do some stuff here
}
VB Version
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
' Do some stuff here
End Sub
In VB it would be:
Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
Mybase.Sub_OverheadClass_Load(e)
End Sub
Your default page should inherit OverheadClass
Partial Public Class _Default
Inherits OverheadClass
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Do some page stuff'
End Sub
End Class
And OverheadClass should inherit System.Web.UI.Page
Public Class OverheadClass
Inherits System.Web.UI.Page
Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyClass.Load
'Do some base stuff'
End Sub
End Class
Partial Class OverheadClass
Inherits System.Web.UI.Page
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
End Class
Partial Class _Default
Inherits OverheadClass
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
End Class