UPDATE
from this i bind gridview
Public Function uplif() As DataTable
Dim dt As New DataTable()
gridvieew1.Visible = True
Try
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("ID", GetType(Integer)),
New DataColumn("Name", GetType(String))}
Dim Content As String = Request.Form(textbox1.UniqueID)
For Each row As String In Content .Split(ControlChars.Lf)
If Not String.IsNullOrEmpty(row) Then
dt.Rows.Add()
Dim i As Integer = 0
For Each cell As String In row.Split(ControlChars.Tab)
If i > 1 Then
labelmessage.Text = "More than 2 columns not Allowed !!"
textbox1.Text = ""
Else
If cell.Trim() = "" Then
cell = "0"
End If
dt.Rows(dt.Rows.Count - 1)(i) = cell
i += 1
End If
Next
End If
Next
gridvieew1.DataSource = dt
gridvieew1.DataBind()
Catch Ex As Exception
labelmessage.CssClass = "alertNo"
labelmessage.Text = Ex.Message
End Try
Return dt
End Function
Protected Sub PasteToGridView(sender As Object, e As EventArgs)
uplif()
End Sub
now when i try to add new row like this
Private Sub AddNewRowToGrid()
Dim dt As DataTable = uplif()
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridvieew1.DataSource = dt
gridvieew1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub
this shows same output like add new row and replace previous data which is already in gridview and also this shows an error
Object reference not set to an instance of an object.
after click on add new row
ID Name
where as i want like this
ID Name
1 abc
2 def
(here new empty row when click on button )
As was pointed out in a comment to your post, the problem is in these two lines:
Dim dt As New DataTable()
...
gridview1.DataSource = dt
That creates a brand new DataTable and binds the grid view to it. You don't copy data over, and you don't alter the existing gridview's table.
The correct fix here would be to get the DataTable from the gridview's DataSource and make any changes you need to to that. Don't create a new DataTable.
Get the already assigned DataSource and then add the Row. Do not add columns as it will be already present in your datasource
Private Sub AddNewRowToGrid()
Dim dt As gridview1.DataSource
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridview1.DataSource = dt
gridview1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub
Related
let say i have 2 text box, 1 button and 1 gridview and i want to add data from textboxs to gridview with a button click.
How can I achive it.
I have tried below code but it replaced the old row.
Private dt As New DataTable
Private Sub Btnidadd_Click(sender As Object, e As EventArgs) Handles Btnidadd.Click
dt.Columns.Add("First Name")
dt.Columns.Add("Last Name")
Dim R As DataRow = dt.NewRow
R("First Name") = textbox1.Text
R("Last Name") = textbox2.Text
dt.Rows.Add(R)
GridView1.DataSource = dt
GridView.DataBind()
When you click the button in ASP.NET, a postback occurs and the page is recreated.
So, you need to keep data somewhere.
For example, if you save it to a session variable like this.
Private dt As DataTable
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
dt = New DataTable
dt.Columns.Add("First Name")
dt.Columns.Add("Last Name")
Session("dt") = dt
Else
dt = CType(Session("dt"), DataTable)
End If
End Sub
Private Sub Btnidadd_Click(sender As Object, e As EventArgs) Handles Btnidadd.Click
Dim R As DataRow = dt.NewRow
R("First Name") = TextBox1.Text
R("Last Name") = TextBox2.Text
dt.Rows.Add(R)
GridView1.DataSource = dt
GridView1.DataBind()
Session("dt") = dt
End Sub
I am using ASP.NET with VB.NET and I want the user add several row to data table.
I am trying to add multi row into data table in run time by (textboxes, rad combo box and check box).
I add first row second and third row.
But when I present the data table its show only the last row I enter
so the table contain only one row.
How do I keep all row in data table not only one row? I tried everything please help.
This is my code:
Dim dcItemID = New DataColumn("ItemID", GetType(Int32))
Dim dcUnit = New DataColumn("UnitID", GetType(Int32))
Dim ItemPrice = New DataColumn("ItemPrice", GetType(Int32))
Dim sellprice = New DataColumn("SellPrice", GetType(Int32))
dt.Columns.Add(dcItemID)
dt.Columns.Add(dcUnit)
dt.Columns.Add(ItemPrice)
dt.Columns.Add(sellprice)
dt.Rows.Add(Convert.ToInt32(rcItemName.SelectedValue), Convert.ToInt32(rcUnitID.SelectedValue), tbItemPrice.Text, tbSellprice.Text)
thank u all i found the answer
if any one interested this is my solution :
Public Class WebForm1
Inherits System.Web.UI.Page
Private dt As DataTable = New DataTable()
Private dr As DataRow = Nothing
Protected Sub btnSaved_Click(sender As Object, e As EventArgs) Handles btnSaved.Click
If ViewState("table") IsNot Nothing Then
dt = CType(ViewState("table"), DataTable)
End If
dr = dt.NewRow()
dr("ItemPrice") = tbItemPrice.Text
dr("SellPrice") = tbSellprice.Text
' dr("Product_Amount") = txtAmount.Text
dt.Rows.Add(dr)
ViewState("table") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ItemPrice")
dt.Columns.Add("SellPrice")
End Sub
End Class
I want to color single Rows when there empty in a Gridview, but it changes the color from every Row empty and not.
Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load
... SQL Connection Stuff
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Dim Menge As Integer = GridView1.Rows.Count - 1
For i = 0 To Menge
For Each row As GridViewRow In GridView1.Rows
If GridView1.Rows(i).Cells(4).Text = "" Then
GridView1.Rows(i).Cells(4).BackColor = System.Drawing.Color.Red
End If
Next
Next
End Sub
Can someone Help me?
You should use the following code in your Default_Load event, but this will only color rows when page loads. Ideally, you should hook up the RowDataBound event with your grid view.
Code if using Default_Load event
Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load
... SQL Connection Stuff
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
'color rows based on some condition
For Each row As GridViewRow In GridView1.Rows
If row.Cells(4).Text = "" Then
row.Cells(4).BackColor = System.Drawing.Color.Red
End If
Next
End Sub
Code if using RowDataBound event
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(4).Text = "" Then
e.Row.Cells(4).BackColor = System.Drawing.Color.Red
End If
End If
End Sub
I have a Gridview filled by a dataTable, filled by a DataAdapter. That's how grid is initially loaded in Page_Load.
To add a search funcionality, I make the same but passing TextBox.Text as parameter to the SELECT... LIKE ... statement.
To add an edit funcionality(a button in every row) I need the previous data in the dataTable, and if I performed a search before editing I need only the result of the search in my dataTable.
The problem is, I don't know how to keep its value alive (persistent), and dataTable has 0 columns when I press teh edit button, so it doesn't display anything to edit.
I guess it happens because I'm using Using, and dataTable is probably getting cleaned after End Using.
In that case, whta can I do to fix it? I thought removing miconn.Close() but it doesn't solve anything, in fact, I don't know if connection is still open after End Using.
Code:
Dim con As New Connection
Dim table As New DataTable()
Private Sub fill_grid()
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
fill_grid()
End If
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim miCon As New Connection
Using miconn As New SqlConnection(miCon.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA WHERE area LIKE #area"
Using command As New SqlCommand(sql, miconn)
command.Parameters.Clear()
command.Parameters.Add("#area", SqlDbType.VarChar).Value = "%" + TextBox1.Text + "%"
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = table
GridView1.DataBind()
End Sub
Protected Sub CancelEditRow(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
GridView1.DataSource = table
GridView1.DataBind()
End Sub
BindGrid()
{
var dt = YourMethodReturningDatatable();
ViewState["Table"] = dt;
grid.DataSource = ViewState["Table"];
grid.Databind();
}
page_load
{
if(not ispostback) // not because my 1 key stopped working.
{
BindGrid();
}
}
I would suggest you to make two different functions for filling the data table and binding it. Call the filling function before the !IsPostBack condition and do the binding inside the condition. Here is the sample code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim table as new DataTable
table = GetData() 'The function that would return a data table
If Not IsPostBack Then
GridView1.DataSource = table
GridView1.DataBind()
End If
End Sub
Private Function GetData() As DataTable
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GetData = table
miconn.Close()
End Using
End Using
End Using
End function
Hope it helps.
I am trying to delete a row from a gridview (based on a condition) and then add than row to another gridview inside of the "master" gridview's RowDataBound event. Originally I did not know that in order to call .DeleteRow(i) you needed to have an "ondelete" event handler. However, since all the gridview's .DeleteRow method does is call this event handler, I am confused as to how to use it. Can someone please help point me in the right direction?
Protected Sub grdProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdProduct.RowDataBound
' Grey out expired products
Dim row As GridViewRow
row = e.Row
Dim incomingDate As String
Dim incomingStatus As String = ""
incomingDate = row.Cells(3).Text.ToString()
incomingStatus = row.Cells(5).Text.ToString()
If (e.Row.RowType <> DataControlRowType.DataRow) Then
Exit Sub
End If
Try
Dim expDate As Date = incomingDate
If (expDate < DateTime.Today Or incomingStatus.Equals("D")) Then
'Create object for RowValues
Dim RowValues As Object() = {"", "", "", "", "", ""}
'Create counter to prevent out of bounds exception
Dim i As Integer = row.Cells.Count
'Fill row values appropriately
For index As Integer = 0 To i - 1
RowValues(index) = row.Cells(index).Text
Next
'create new data row
dProdRow = dProdtable.Rows.Add(RowValues)
dProdtable.AcceptChanges()
grdProduct.DeleteRow(e.Row.RowIndex)
End If
Catch ex As Exception
End Try
End Sub
Protected Sub grdProduct_Delete(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdProduct.RowDeleting
'Not sure what to do here
End Sub
The best way to do this is to manipulate this at the datasource level rather than manipulating the UI components themselves.
For example:
if(!IsPostback)
{
DataTable one = ...
DataTable two = ...
var removeRows = (from c in one.AsEnumerable()
where c.Field<DateTime>("incomingDate")< incomingDate ||
c.Field<string>("incomingStatus")=="D"
select c).ToList();
for(var item in removeRows)
{
two.ImportRow(item);
}
//now delete from initial table
foreach(var item in removeRows)
{
one.Rows.Remove(item);
}
//Now bind both grids
grid1.DataSource=one;
grid1.DataBind();
grid2.DataSource=two;
grid2.DataBind();
}
Update - Sample toy program in VB.NET Hopefully you can adapt it to your situation.
Sub Main
Dim one As New DataTable()
one.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = one.NewRow()
r.ItemArray = New Object() {i}
one.Rows.Add(r)
Next
Dim two As New DataTable()
two.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = two.NewRow()
r.ItemArray = New Object() {i}
two.Rows.Add(r)
Next
Dim removeRows = (From c In one.AsEnumerable() Where c.Field(Of Integer)("one") = 5).ToList()
For Each item As DataRow In removeRows
two.ImportRow(item)
Next
For Each item As DataRow In removeRows
one.Rows.Remove(item)
Next
End Sub
I just realized that you are using VB.NET. You should be able to translate the above from C# to VB.NET. The general idea is there, anyway.