Asp.net Grid View - asp.net

In my Grid View ,When a button is clicked,i want to insert that row in to database and at the same time make the row invisible in the Grid View.
I can insert in to database but can't make the inserted row invisible.
Dim PayID As Integer = (e.CommandArgument)
Dim EmpID As Integer = (e.CommandArgument)
Dim EID As Integer = CType(Dg1.DataKeys(EmpID).Values("EmpID"), Integer)
Dim PID As Integer = CType(Dg1.DataKeys(PayID).Values("PayID"), Integer)
cmd.CommandText = "Insert into EmployDetails(EmpID,PayID,PayDate)
Values(" & EID & " ," & PID & ",GetDate())"
cmd.ExecuteNonQuery()
Thank You

You might need to bind the GridView to a DataView instead of a DataSet. Then when you add a row update the DataView to exclude the new row.

After insering your row to db, you should remove the related record from datasource (datatable, dataview) and rebind your gridview.
EDIT :
After your Insert operation :
1. take your remove the related row from your datasource :
Dim insertedRows As DataRow() = myDataTable.Select("ID = " & id)
For Each dr As DataRow In insertedRows
myDataTable.Rows.Remove(dr)
Next
2. And after that re-bind your gridview :
gridView.DataSource = myDataTable
gridView.DataBind()
NOTE : I use a converter to convert codes C# to VB. Hope it's ok.

Related

Is it possible to select from selected checklist SQL Server

I have a query select and i need is to select the data in selected checkbox list. Is it possible?
This is my query: Im tring to use -IN- but i think this is not the solution
SELECT [scod], [ecode], [scty] ,[sonm] FROM [Z_ALI].[dbo].[M_STORE] WHERE [scod] IN ('FROMTHECHECKLIST')
I' trying to do like this:
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim CheckRow As CheckBox = (TryCast(row.Cells(1).FindControl("chckSelector"), CheckBox))
If CheckRow.Checked Then
Dim scode As String = TryCast(row.Cells(2).FindControl("lblsstorecode"), Label).Text
Dim sql As String = "SELECT [scod], [ecode], [scty] ,[sonm] FROM [Z_ALI].[dbo].[M_STORE] WHERE [scod] IN ('+scode+')"
Using cmd As New SqlCommand(sql)
Using dtViewing As Data.DataTable = code.GetData(cmd, "NSP", code.HRIS, "SELECT")
If code.err = String.Empty Then
GridView4.DataSource = dtViewing
GridView4.DataBind()
Else
code.setStatus(code.err, Me.Page, "")
End If
End Using
End Using
End If
End If
Next
For example this is the selected list from checkboxlist
Checklist
-|351530928006|
0|351530928007|
0|351530928008|
0|351530928009|
-|3515309280010|
zero is the selected
- is not selected
Is it possible to get or iterate all the list from the query.
SELECT scod,ecode,scty,sonm
FROM M_STORE
WHERE scod IN (Checklist(0), Checklist(1), Checklist(2)...)
or have your checklist in sql table and do this
SELECT scod,ecode,scty,sonm
FROM M_STORE
WHERE scod IN (SELECT scod FROM ChecklistTable)

Read multiple items from list box to query information from a database

Ok so what I'm trying to do is allow the users of my web form in asp.net to select multiple assets from a list box. When they select these assets and press the select button it fires the following code which should run through the selected indices, query the DB for the description and asset tag's, and populate the Description and Asset tag boxes with those values. Working through this I've been able to get it to read the values from the database and populate the fields but it would only populate the value from the first selected item and it would just insert the same value equal to the number of times equal to the number of items selected in the inbox. I tried my current code to run through the indices a little better but it seems to be failing the If statement and I just can't figure out why. Any help is appreciated, thanks everyone!
Dim i As Integer
For i = 0 To lstAssets.GetSelectedIndices.Count
If lstAssets.Items(i).Selected = True Then
Dim str2 As String = lstAssets.Items(i).Value.ToString
Dim cs As New OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings("CSIWebUpd").ConnectionString)
Dim ds As String = cs.DataSource
Dim cn As OracleConnection = New OracleConnection("user id=webupd;password=webupd;data source=" + ds)
Dim sql As String = "SELECT description, tag FROM assets WHERE id = :id"
Dim cmd As New OracleCommand(sql, cn)
cmd.Parameters.Add(":id", OracleDbType.Varchar2).Value = str2
cmd.CommandType = CommandType.Text
cmd.BindByName = True
cn.Open()
Dim dr As OracleDataReader = cmd.ExecuteReader()
cmd.ExecuteNonQuery()
dr.Read()
desc = dr.GetString(0).ToString
ass = dr.GetString(1).ToString
If txtDescription.Text = Nothing Then
txtDescription.Text = dr.GetString(0).ToString
Else
txtDescription.Text = txtDescription.Text + Chr(13) + Chr(10) + dr.GetString(0).ToString
End If
If txtAsset.Text = Nothing Then
txtAsset.Text = dr.GetString(1).ToString
Else
txtAsset.Text = txtAsset.Text + Chr(13) + Chr(10) + dr.GetString(1).ToString
End If
cmd.Dispose()
cn.Close()
End If
Next i
UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional
UpdatePanel1.Update()
I would work with the SelectedIndices values in this way
For Each i in lstAssets.GetSelectedIndices
Now i contains the index of the items selected not the offset of the GetSelectedIndices array
The GetSelectedIndices returns an array where every element of the array is the index in the Items collection where you have an item selected.
An example could explain better:
Supposing the the items selected are 1, 5 6 (Count=3), your code set the value of i to 0,1,2 and then uses that value to lookup the ID in the items collection, but the following check on lstAssets.Items(i).Selected found just the item at index 1 as selected. Instead using the for each approach you get the values 1,5,6.

Find nested gridview in user defined function

I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

how to clear off gridview?

I'm creating a dynamic gridview function which will bind different tables from DB into a datatable and then assign the datatable to the gridview! This is how it works, i have a dropdownlist, gridview and a button, the button will fire specific function based on the dropdownlist selection and then gridview will bind the data, my problem is that, when u press the button for the 1st time, the gridview will bind the data from DB, for second time pressing, the gridview will duplicate the data from the data of 1st time pressing! how do i clear off the gridview to avoid data duplication?
Private Sub Login()
sSql = "" & _
"SELECT TYPE, SUBTYPE, LOGTS, ACTION, USERID, STAT1 " & _
"FROM i_LOG " & _
"WHERE TYPE = 'USR' AND SUBTYPE = 'LOG' " & _
"AND CONVERT(VARCHAR(20), LOGTS, 103) >= '" & txtDTFrom.Text & _
"' AND CONVERT(VARCHAR(20), LOGTS, 103) <= '" & txtDTTo.Text & "'"
DT = CreateDataTable(sSql) 'Retrieve from database.
Session(sSesDT) = DT
GVM.DataTable = DT
GVM.GVAddEmptyRow()
Dim seq As New BoundField
Dim Type As New BoundField
Dim SubType As New BoundField
Dim Logts As New BoundField
Dim action As New BoundField
Dim user As New BoundField
Dim status As New BoundField
seq.HeaderText = GVM.DTNumberField
seq.DataField = GVM.DTNumberField
Type.HeaderText = "Type"
Type.DataField = "TYPE"
SubType.HeaderText = "Subtype"
SubType.DataField = "SUBTYPE"
Logts.HeaderText = "Date and Time"
Logts.DataField = "LOGTS"
action.HeaderText = "Action"
action.DataField = "ACTION"
user.HeaderText = "User ID"
user.DataField = "USERID"
status.HeaderText = "Status"
status.DataField = "STAT1"
gv.AutoGenerateColumns = False
gv.Columns.Add(Type)
gv.Columns.Add(SubType)
gv.Columns.Add(Logts)
gv.Columns.Add(action)
gv.Columns.Add(user)
gv.Columns.Add(seq)
gv.Columns.Add(status)
gv.DataSource = Session(sSesDT)
gv.DataBind()
End Sub
Private Overloads Function CreateDataTable(ByVal sSql As String) As DataTable
Dim DA As New OleDb.OleDbDataAdapter
Dim dtDataTbl As New DataTable
Dim dcDataCol As New DataColumn
With DBMgr
.openCnn()
.SQL = sSql
.openRst()
DA.Fill(dtDataTbl, .rst)
End With
'==Adding Columns==
dcDataCol = New DataColumn 'No
With dcDataCol
.DataType = GetType(Int32)
.ColumnName = GVM.DTNumberField
.AutoIncrement = True
'.AllowDBNull = True
End With
dtDataTbl.Columns.Add(dcDataCol)
'**Adding Columns**
Return dtDataTbl
End Function
Sorry, this is in C#, but just call it before you bind any new data and it'll clear any existing data... unless of course the problem is that the DataSource you are assigning has the duplicated data.
gridview.DataSource=null;
gridview.DataBind();
Also, just to note, you are adding every column in every time that procedure is called? You need to run:
gridview.Columns.Clear();
You can reset it's data source and rebind it for example
gv.datasource=""
gv.databind()
and then reuse it
Usually this does not happen when you rebind grid like:
grid.DataSource = 'NEW_DATA_SOURCE'
grid.DataBind
I think may be the problem is in your function fetching data:
CreateDataTable(sSql)
Please check inside this if you are fetching data every time into a new DataTable or using same one (may be declared at global scope or passed from your class to data accessing component). I'd lost whole night once to fix this :(
Place your gridview in a table with an id:
<table id="myTable" border="0">
<tr><td>
<asp:GridView Width="765px" ID="mygrid" runat="server">
...
...
</asp:GridView>
</td></tr></table>
Then call from a button click your javascript function:
function clearGridview()
{
var rows = document.getElementById('myTable').getElementsByTagName('tbody') [0].getElementsByTagName('tr').length;
if(rows!=0)
document.getElementById("myTable").deleteRow(0);
}

Resources