Gridview update not working - asp.net

When i click on EDIT button in Grid, it amke all fields editable and provides two options(Update and Cancel). In this Grid, there are two dropdownlists, 3 calenders and some textboxes. If i click on update then all the textbox values updated in the database, but all other fields(dropdown and calender) values in database is automatically NULL.
Below is the main page GridView code:
<asp:GridView ID="GridView1" runat="server" CellPadding="5" ForeColor="#333333" width="1000px"
GridLines="None" OnPageIndexChanging="gridView_PageIndexChanging"
AllowSorting="True" OnSorting="gridView_Sorting" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating"
BorderStyle="Outset" CellSpacing="1" Font-Names="Cambria"
Font-Size="Small" AllowPaging="True" ShowFooter="True"
ShowHeaderWhenEmpty="True"
DataSourceID="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="case_number" HeaderText="Case Number"
SortExpression="case_number" />
<asp:BoundField DataField="case_name" HeaderText="Case Name"
SortExpression="case_name" />
<asp:BoundField DataField="Case_Type_Text" HeaderText="Case Type"
SortExpression="Case_Type_Text" />
<asp:TemplateField HeaderText="Case Status" SortExpression="Case_Status_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource3" DataTextField="Case_Status_Text" DataValueField="Case_Status_Text"
SelectedValue='<%# Bind("Case_Status_Text") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Case_Status_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="assigned_date" HeaderText="Assigned Date"
SortExpression="assigned_date" DataFormatString="{0:d}" />
<asp:BoundField DataField="assigned_to" HeaderText="Assigned To"
SortExpression="assigned_to" />
<asp:TemplateField HeaderText="Date Withdrawn" SortExpression="date_withdrawn">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker5" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("date_withdrawn", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Delivered" SortExpression="date_delivered">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker7" runat="server"
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server"
Text='<%# Bind("date_delivered", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC By" SortExpression="qc_by">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name" DataValueField="User_Name"
SelectedValue='<%# Bind("qc_by") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("qc_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC Date" SortExpression="qc_date">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker6" runat="server"
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("qc_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Notes">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("additional_notes") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("additional_notes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ButtonType="Button"
CausesValidation="False" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:con %>"
ProviderName="<%$ ConnectionStrings:con.ProviderName %>"
SelectCommand="SELECT * FROM [View_Intakesheet]"
UpdateCommand="UPDATE intakesheet SET case_number = #case_number, case_name=#case_name, Case_Type=#case_type, Case_Status = #case_status, assigned_date = #assigned_date, assigned_to = #assigned_to, date_withdrawn= #date_withdrawn, date_delivered= #date_delivered, qc_by = #qc_by, qc_date=#qc_date, additional_notes = #additional_notes WHERE (case_number = #case_number)">
<UpdateParameters>
<asp:Parameter Name="case_number"/>
<asp:Parameter Name="case_name" />
<asp:Parameter Name="case_type" />
<asp:Parameter Name="case_status" />
<asp:Parameter Name="assigned_date" Type="DateTime" />
<asp:Parameter Name="assigned_to" />
<asp:Parameter Name="date_withdrawn" Type="DateTime" />
<asp:Parameter Name="date_delivered" Type="DateTime" />
<asp:Parameter Name="qc_by" />
<asp:Parameter Name="qc_date" Type="DateTime" />
<asp:Parameter Name="additional_notes" />
</UpdateParameters>
</asp:SqlDataSource>
</td>
</tr>
Below is the Update event::
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.FindControl("case_type");
DropDownList cs = (DropDownList)row.FindControl("case_status");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
con.Close();
bind();
}
public void bind()
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from intakesheet", con);
DataSet ds = new DataSet();
da.Fill(ds, "intakesheet");
//GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
con.Close();
}

SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
change this line
mainly problem with these
Case_Type = Case_Type, Case_Status = Case_Status, in update query
DropDownList ct = (DropDownList)row.FindControl("case_type");
DropDownList cs = (DropDownList)row.FindControl("case_status")
;
send ct.SelectedIndex.value if want to send ids if you have bind with its value
if you want send selected index
then
send
dt.SelectedText
like
Case_Type = ct.SelectedItem.Text, Case_Status = cs.SelectedItem.Text
check this line
DropDownList cs = (DropDownList)row.FindControl("DropDownList3")
similary give the correct id for case type
in above line you are passing the ids of dropdown, you should send either its selected value of its selected index
changes
SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
cmd.parameters.add("#case_number",sqldbtype.nvarchar).value = case_number // the string variable of case number
do similar for others parameters

I also had a problem with a GridView that was not updating. Inspection of the e.Newvalues Dictionary in the GridView's RowUpdating event showed that the old values for the record were being sent to the database UPDATE query. DataKeyNames was not my problem; I had it set correctly. The WHERE clause of my SELECT query referenced a control parameter against a TextBox on my form. I had inadvertently set EnableViewState for this textbox to "False". Because of this, the GridView was rebinding itself before the UPDATE occurred. Setting EnableViewState on the TextBox to "True" fixed the problem. Here is the code to see the UPDATE parameters:
Protected Sub MyGridView_RowUpdating _
(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
Handles MyGridView.RowUpdating
' Inspect the parameters being sent to the database for an ASP NET GridView UPDATE.
Dim I As Integer
I = 0
For Each MVO As System.Collections.DictionaryEntry In e.OldValues
If MVO.Value Is DBNull.Value OrElse MVO.Value Is Nothing Then
Debug.Print(I.ToString + ": " + MVO.Key + " Value: ")
Else
Debug.Print(I.ToString + ": " + MVO.Key + " Value: " + MVO.Value.ToString)
End If
I += 1
Next MVO
I = 0
For Each MVN As System.Collections.DictionaryEntry In e.NewValues
If MVN.Value Is DBNull.Value OrElse MVN.Value Is Nothing Then
Debug.Print(I.ToString + ": " + MVN.Key + " Value: ")
Else
Debug.Print(I.ToString + ": " + MVN.Key + " Value: " + MVN.Value.ToString)
End If
I += 1
Next MVN
End Sub

Related

How to get the ID of the record in the GridViewRow in loop?

Aim: Gridview with checkbox on each line, user then clicks a button and all ticked lines are actioned in the button code. I need the ID's of all the records where the CheckBox is checked.
Error:
Object reference not set to an instance of an object.
on row: ID_Current = row.FindControl("ID").ToString
if I change the to ID_Current = DirectCast(row.FindControl("cbSelect"), CheckBox).Checked I get 'True' as a result but I already know that and want to get the ID.
Aspx-Code with my Gridview:
<asp:Panel ID="ActionGrid" runat="Server">
<h2>Actions To Edit</h2>
<asp:GridView ID="GridView3" runat="server" AllowPaging="True" AllowSorting="True" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="UPRN" DataSourceID="SqlDataSource3" EmptyDataText="There are no data records to display." Font-Size="Medium" PagerStyle-CssClass="pgr" Width="1000px">
<%-- AutoGenerateEditButton="True"--%>
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ControlStyle-Width="50px" DataField="UPRN" HeaderText="UPRN" ReadOnly="True" SortExpression="UPRN" />
<asp:BoundField DataField="LocationItemPosition" HeaderText="Location Item Position" ReadOnly="True" SortExpression="LocationItemPosition" />
<asp:TemplateField HeaderText="Surveye" SortExpression="SurveyDate">
<ItemTemplate>
<asp:Label ID="lblSurveyDate" runat="server" Text='<%# apFunctionCharacters.fncDateTidy(Eval("SurveyDate"))%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemRef" HeaderText="Item Ref" ReadOnly="True" SortExpression="ItemRef" />
<asp:BoundField DataField="OverallRiskCategory" HeaderText="Overall Risk Category" ReadOnly="True" SortExpression="OverallRiskCategory" />
<asp:BoundField DataField="Comments" HeaderText="Comments" ReadOnly="True" SortExpression="Comments" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
<asp:Button ID="btnChangeToNA" runat="server" CssClass="Button" Text="Change to NA" />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</asp:Panel>
Submit button:
<asp:Button ID="btnChangeToNA" runat="server" CssClass="Button" Text="Change to NA" />
.aspx.vb stored procedure/action code
Protected Sub btnChangeToNA_Click(sender As Object, e As EventArgs) Handles btnChangeToNA.Click
For Each row As GridViewRow In GridView3.Rows
Dim ID_Current As String = ""
'read the label
If DirectCast(row.FindControl("cbSelect"), CheckBox).Checked Then
ID_Current = row.FindControl("ID").ToString
' change value
'############stored procedure here
Dim connection As SqlConnection
Dim command As New SqlCommand
Dim ds As New DataSet
Dim ConnectionString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("MY_SQL").ToString()
connection = New SqlConnection(ConnectionString1)
connection.Open()
With command
.Connection = connection
.CommandText = "spChangeValue "
.CommandType = CommandType.StoredProcedure
.Parameters.Clear()
.Parameters.AddWithValue("#ID_Current", ID_Current)
.ExecuteNonQuery()
End With
'#############################
lblTest.Text += ID_Current
End If
'Loop
Next
End Sub
With FindControl you find controls(what suprise) not strings. And you have to pass the ID of the control not a property like Id.
So this doesnt make much sense:
Dim ID_Current As String = row.FindControl("ID").ToString()
Instead you could store the ID in a HiddenField, so on aspx:
<asp:HiddenField ID="HiddenID" runat="server" Value='<%# Eval("ID_Current") %>' />
Now you can get the reference to this HiddenField with FindControl:
Dim hiddenID As HiddenField = DirectCast(row.FindControl("HiddenID"), HiddenField)
Dim ID_Current As String = hiddenID.Value
You need a control with the id "ID"
<ItemTemplate>
<asp:HiddenField ID="ID" runat="server" Value='<%# FillMeSomehow%>' />
<asp:CheckBox ID="cbSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>

Inconsistency with dropdowns displaying values in gridview

I'm having a problem with my dropdown lists in my child gridview displaying values. For whatever reason the first dropdown in the row works fine and displays the values from the database, the other ones don't display anything.
Below is the code for my gridviews:
<asp:GridView ID="GVAccounts" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="Horizontal"
style="position: relative; margin-top: 10px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="branch" HeaderText="Branch"
SortExpression="branch" />
<asp:BoundField DataField="no" HeaderText="Account"
SortExpression="account" />
<asp:TemplateField HeaderText="Name" SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text='<%# Eval("name") + " " + Eval("surname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="type" HeaderText="Type" SortExpression="type" />
<asp:BoundField DataField="sub" HeaderText="Sub" SortExpression="sub" />
<asp:BoundField DataField="TotalAmount" HeaderText="Hold"
SortExpression="TotalAmount" />
<asp:BoundField DataField="loc" HeaderText="LOC" DataFormatString="{0:C}" SortExpression="loc" />
<asp:BoundField DataField="locstatus" HeaderText="LOC status"
SortExpression="locstatus" />
<asp:BoundField DataField="HoldCalc" HeaderText="OD/EX Amt" SortExpression="HoldCalc" />
<asp:BoundField DataField="odtimes" HeaderText="#OD" SortExpression="odtimes" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="gridChild" style="display: inline; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false"
BorderStyle="Double" BorderColor="#5D7B9D" Width="80%">
<HeaderStyle BackColor="#5D7B9D" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"
oncheckedchanged="chkSelect_CheckedChanged" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="effective" HeaderText="Effective"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="desc_" HeaderText="Desc"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="code" HeaderText="TC"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="amount" HeaderText="Amount"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="tracer" HeaderText="Cheq #"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="empl" HeaderText="Empl"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="balance" HeaderText="OD/EXT Amt"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Note">
<ItemTemplate>
<asp:DropDownList ID="DropDownNote" runat="server"
onselectedindexchanged="DropDownNote_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>MWC</asp:ListItem>
<asp:ListItem>CBM</asp:ListItem>
<asp:ListItem>Return</asp:ListItem>
<asp:ListItem>TSF</asp:ListItem>
<asp:ListItem>OK NO S/C</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Note1">
<ItemTemplate>
<asp:DropDownList ID="ddNote2" runat="server"
onselectedindexchanged="ddNote2_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Selected="True">NSF</asp:ListItem>
<asp:ListItem>Funds Not Clear</asp:ListItem>
<asp:ListItem>Post Dated</asp:ListItem>
<asp:ListItem>Stale Dated</asp:ListItem>
<asp:ListItem>Stop Payment</asp:ListItem>
<asp:ListItem>Encoding Incorrect</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch">
<ItemTemplate>
<asp:DropDownList ID="ddBranch" runat="server" DataSourceID="BranchDataSource"
DataTextField="branch" DataValueField="branch" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="BranchDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ThirdPartyDataConnectionString %>"
SelectCommand="SELECT [branch] FROM [branch]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Account">
<ItemTemplate>
<asp:TextBox ID="TextNo" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="ddType" runat="server" DataSourceID="typeSource"
DataTextField="Type" DataValueField="Type" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="typeSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ThirdPartyDataConnectionString %>"
SelectCommand="SELECT [Type] FROM [DMDType]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub">
<ItemTemplate><asp:TextBox ID="TextSub" Width="25px" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="GVFixedHeader" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Below is the method that is having the issue with displaying:
Private Function CheckForSubmit() As Boolean
Try
conn = New SqlConnection(connectionString)
Dim cmdNote As New SqlCommand("select note, note1, noteBranch, noteAccountNo, noteType, noteSub, id from DmdOD where id = #id order by effective, time_, seqno_dmddmhi_dmhi", conn)
cmd = New SqlCommand("select submitted, id, effective FROM DmdOD where no = #no and entered = '" & ddDate.SelectedItem.Text & "' order by effective, time_, seqno_dmddmhi_dmhi", conn)
Dim objDBId As Object = 0
Dim id = 0
Dim objDate As Date
Dim dateStr As String = ""
If ddDate.SelectedIndex <> -1 Then
cmd = New SqlCommand("select submitted, id, entered FROM DmdOD where no = #no and entered = '" & ddDate.SelectedItem.Text & "' order by effective, time_, seqno_dmddmhi_dmhi", conn)
' cmd.Parameters.Add(New SqlParameter("effective", ddDate.SelectedItem.Text))
Else
cmd = New SqlCommand("select submitted, id, entered FROM DmdOD where no = #no order by effective, time_, seqno_dmddmhi_dmhi", conn)
End If
cmd.CommandType = CommandType.Text
Dim i = 0
For Each row As GridViewRow In GVAccounts.Rows
cmd.Parameters.Add(New SqlParameter("#no", row.Cells(1).Text))
Dim gv As GridView = DirectCast(row.FindControl("gvChildGrid"), GridView)
conn.Open()
Dim idReader As SqlClient.SqlDataReader = cmd.ExecuteReader()
'get ids in order
While (idReader.Read())
If Not objId.Contains(idReader.GetValue(1)) Then
objId.Add(idReader.GetValue(1))
End If
End While
conn.Close()
conn.Open()
Dim reader As SqlClient.SqlDataReader = cmd.ExecuteReader()
While (reader.Read())
objSubmit = reader.GetValue(0)
objDBId = reader.GetValue(1)
objDate = reader.GetValue(2)
dateStr = objDate.ToShortDateString
If dateStr = ddDate.SelectedItem.Text Then
Exit While
End If
End While
conn.Close()
If objSubmit = True And dateStr = ddDate.SelectedItem.Text Then
For Each r As GridViewRow In gv.Rows
cmdNote.Parameters.Add(New SqlParameter("#id", objId(i)))
Dim ddNote As Control = r.FindControl("DropDownNote")
Dim ddl As DropDownList = DirectCast(ddNote, DropDownList)
Dim ddNote2 As Control = r.FindControl("ddNote2")
Dim ddlNote As DropDownList = DirectCast(ddNote2, DropDownList)
ddlNote.Items.Insert(0, New ListItem(String.Empty, String.Empty))
Dim ddBranch As Control = r.FindControl("ddBranch")
Dim ddBranchBox As DropDownList = DirectCast(ddBranch, DropDownList)
ddBranchBox.Items.Insert(0, New ListItem(String.Empty, String.Empty))
Dim txtAccount As Control = r.FindControl("TextNo")
Dim txtAccountBox As TextBox = DirectCast(txtAccount, TextBox)
Dim ddType As Control = r.FindControl("ddType")
Dim ddTypeBox As DropDownList = DirectCast(ddType, DropDownList)
Dim txtSub As Control = r.FindControl("TextSub")
Dim txtSubBox As TextBox = DirectCast(txtSub, TextBox)
r.Cells(0).Enabled = False
r.Cells(8).Enabled = False
r.Cells(9).Enabled = False
r.Cells(10).Enabled = False
r.Cells(11).Enabled = False
r.Cells(12).Enabled = False
r.Cells(13).Enabled = False
'Display fields
gv.Columns(8).Visible = True
gv.Columns(9).Visible = True
gv.Columns(10).Visible = True
gv.Columns(11).Visible = True
gv.Columns(12).Visible = True
gv.Columns(13).Visible = True
ddBranchBox.Visible = True
txtAccount.Visible = True
ddTypeBox.Visible = True
txtSub.Visible = True
'Get Data for fields
conn.Open()
cmdNote.ExecuteNonQuery()
Dim readNotes As SqlClient.SqlDataReader = cmdNote.ExecuteReader()
readNotes.Read()
'Note
If IsDBNull(readNotes.GetValue(0)) Then
ddl.SelectedItem.Text = ""
Else
ddl.SelectedItem.Text = readNotes.GetValue(0)
End If
'Note1
If IsDBNull(readNotes.GetValue(1)) Then
'GVAccounts.Columns(12).Visible = False
ddlNote.Visible = False
ddlNote.SelectedItem.Text = ""
Else
'ddlNote.SelectedItem.Text = readNotes.GetValue(1)
ddlNote.SelectedItem.Selected = False
ddlNote.Items.FindByText(readNotes.GetValue(1)).Selected = True
End If
'Branch
If IsDBNull(readNotes.GetValue(2)) Then
ddBranchBox.Visible = False
ddBranchBox.SelectedItem.Text = ""
Else
ddBranchBox.SelectedItem.Text = readNotes.GetValue(2)
End If
'Account
If IsDBNull(readNotes.GetValue(3)) Then
txtAccountBox.Visible = False
txtAccountBox.Text = ""
Else
txtAccountBox.Text = readNotes.GetValue(3)
End If
'Type
If IsDBNull(readNotes.GetValue(4)) Then
ddTypeBox.Visible = False
ddTypeBox.SelectedItem.Text = ""
Else
ddTypeBox.SelectedItem.Text = readNotes.GetValue(4)
End If
'Sub
If IsDBNull(readNotes.GetValue(5)) Then
txtSubBox.Visible = False
txtSubBox.Text = ""
Else
txtSubBox.Text = readNotes.GetValue(5)
End If
conn.Close()
i += 1
cmdNote.Parameters.Clear()
Next
ButtonSubmit.Enabled = False
ButtonSave.Enabled = False
ButtonSaveTop.Enabled = False
End If
i = 0
'cmd.Parameters.Clear()
'cmdNote.Parameters.Clear()
objSubmit = False
dateStr = ""
cmd.Parameters.RemoveAt(0)
cmdNote.Parameters.Clear()
objId.Clear()
Next
If objSubmit = True Then
Return objSubmit
End If
Catch ex As Exception
LblErr.ForeColor = Drawing.Color.DarkRed
LblErr.Text = "CheckForSubmit - " & ex.Message
Finally
conn.Dispose()
End Try
Return Nothing
End Function
Edit: I should also note that when I step through the code I see that the dropdowns do in fact have values, yet nothing is being displayed for them on the gridview, I'm stumped.
Updated answer
I would compare drop down lists "note" and "note1"
e.g. note works but note1 doesn't.
The difference I can see between the 2 is that note has an empty list item. Try adding an empty list item to note 1.
Failing that, copy the working code from note and gradually replace it with the values from Note1, checking if/when it fails.

Error in exporting selected rows from Gridview to Excel

I am trying to export selected columns from GridView to Excel, and every time I run the code an error pops up with some new .dll file name. What could be the issue? Please find the code below for your reference.
<asp:Panel ID="general" runat="server" BorderColor="#333333" BorderStyle="Double" CssClass="emailpnl" Width="800px">
<asp:GridView ID="bestpractgrv" runat="server" AutoGenerateColumns="False" OnLoad="bestpractgrv_Load" CellPadding="3" GridLines="Vertical" Width="100%" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" AllowPaging="True" OnPageIndexChanging = "OnPaging">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" onclick="CheckAllEmp(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID ="boolcb" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%# Bind("iID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discipline ID">
<ItemTemplate>
<asp:Label ID="discplnlbl" runat="server" Text='<%# Bind("iDisciplineID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Created">
<ItemTemplate>
<asp:Label ID="dateclbl" runat="server" Text='<%# Bind("dDateCreated")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="bptitlelbl" runat="server" Text='<%# Bind("cBPTitle")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</asp:Panel>
VB Code
Private Sub PopulateCheckBoxArray()
Dim CheckBoxArray As ArrayList
If ViewState("CheckBoxArray") IsNot Nothing Then
CheckBoxArray = DirectCast(ViewState("CheckBoxArray"), ArrayList)
Else
CheckBoxArray = New ArrayList()
End If
Dim CheckBoxIndex As Integer
Dim CheckAllWasChecked As Boolean = False
Dim chkAll As CheckBox = DirectCast(bestpractgrv.HeaderRow.Cells(0).FindControl("chkboxSelectAll"), CheckBox)
Dim checkAllIndex As String = "chkboxSelectAll-" & bestpractgrv.PageIndex
If chkAll.Checked Then
If CheckBoxArray.IndexOf(checkAllIndex) = -1 Then
CheckBoxArray.Add(checkAllIndex)
End If
Else
If CheckBoxArray.IndexOf(checkAllIndex) <> -1 Then
CheckBoxArray.Remove(checkAllIndex)
CheckAllWasChecked = True
End If
End If
For i As Integer = 0 To bestpractgrv.Rows.Count - 1
If bestpractgrv.Rows(i).RowType = DataControlRowType.DataRow Then
Dim chk As CheckBox = DirectCast(bestpractgrv.Rows(i).Cells(0).FindControl("boolcb"), CheckBox)
CheckBoxIndex = bestpractgrv.PageSize * bestpractgrv.PageIndex + (i + 1)
If chk.Checked Then
If CheckBoxArray.IndexOf(CheckBoxIndex) = -1 AndAlso Not CheckAllWasChecked Then
CheckBoxArray.Add(CheckBoxIndex)
End If
Else
If CheckBoxArray.IndexOf(CheckBoxIndex) <> -1 OrElse CheckAllWasChecked Then
CheckBoxArray.Remove(CheckBoxIndex)
End If
End If
End If
Next
ViewState("CheckBoxArray") = CheckBoxArray
End Sub
And I get the error on following line
Dim chkAll As CheckBox = DirectCast(bestpractgrv.HeaderRow.Cells(0).FindControl("chkboxSelectAll"), CheckBox)
This is the error message
An exception of type 'System.NullReferenceException' occurred in App_Web_pqx0e3wy.dll but was not handled in user code
After every compilation the dll name changes, while App_Web_XXXX.dll remains constant

how to use delete command in grid view for updation

i have 3 web pages. admin,student and teacher. i have used grid view on each of this page.my table is having a column as 'status'.which is having default value 0. I want to update this value to 1 when i click on delete in gridview. I have written following code. But it is not working.pls help.
this is .aspx file code-
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TEMPRUJUConnectionString %>"
SelectCommand="SELECT * FROM [login] WHERE ([username] = #username)"
DeleteCommand="UPDATE [login] SET [status]= 1 WHERE [id]=#id"
InsertCommand="INSERT INTO [login] ([name], [midname], [surname], [username], [password], [contact], [dob], [email], [address], [occupation], [ltype]) VALUES (#name, #midname, #surname, #username, #password, #contact, #dob, #email, #address, #occupation, #ltype)"
UpdateCommand="UPDATE [login] SET [name] = #name, [midname] = #midname, [surname] = #surname, [username] = #username, [password] = #password, [contact] = #contact, [dob] = #dob, [email] = #email, [address] = #address, [occupation] = #occupation, [ltype] = #ltype WHERE [Id] = #Id">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
and this is my code behind-
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SNEHAL-PC\\SNEHAL1;Initial Catalog=TEMPRUJU;Integrated Security=True");
SqlCommand cmd;
SqlDataReader dr;
con.Open();
GridViewRow row = GridView1.Rows[e.RowIndex];
cmd=new SqlCommand("Update login set status=1 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'",con);
dr = cmd.ExecuteReader();
}
when you have SqlDataSource you have no need to implement GridView1_RowDeleting,
first you must tell to SqlDataSource that where it can find the value of delete command parametr(s), in your case #id... for this, you need to set DataKeyNames property on your GridView by database unique key field name, in your case id...
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
then, to set delete command parameter on SqlDataSource you must tell that, find value of #id from SelectedDataKey property, from GridView like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TEMPRUJUConnectionString %>"
DeleteCommand="UPDATE [login] SET [status]= 1 WHERE [id]=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
and finaly, you need to, send a Delete command with your gridView, for this, you can enable deleteing on gridview control to add this <asp:CommandField ShowDeleteButton="True" /> into your grid view markup, or you can convert this field into a TemplateFiled and create your own template with any control _which have_ CommandName property, and set that property (CommandName) to keyword Delete like this :
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" Text="Delete me"></asp:LinkButton>
this is a sample with Template Field:
<asp:GridView ID="GridView2" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" SortExpression="UserID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("UserID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
DeleteCommand="UPDATE Profiles SET Age = Age+1 where id = #id" SelectCommand="SELECT * FROM Profiles">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
and this is a sample with just enable deleteing :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
DeleteCommand="UPDATE Profiles SET Age = Age+1 where id = #id" SelectCommand="SELECT * FROM Profiles">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
i increment age in my sample by every delete command

delete selected rows from gridview on selecting option from a dropdownlist located outside the gridview

I have a dropdownlist and a gridview control. DropDownlist is outside the gridview.
Dropdownlist contains an option Delete.
Gridview contains checkbox so that rows can be selected.
here is the gridview code:
<asp:GridView ID="gvRefDetail" runat="server" CssClass="mGrid" AutoGenerateColumns="False"
PageSize="50" Font-Names="Segoe UI" Font-Size="10pt" Width="800" AllowPaging="true"
BackColor="White" BorderColor="Silver" EmptyDataText="No Record" BorderStyle="Double"
BorderWidth="1px" CellPadding="4">
<HeaderStyle BackColor="red" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" /></HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NameofReferred">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("NameofReferred") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("NameofReferred")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerName">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("CustomerName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("CustomerName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#CCFFFF" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="White" Font-Bold="True" ForeColor="Gray" BorderColor="Gray" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
c# code:
protected void ddlaction_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlaction.SelectedValue == "1")
{
GridViewRow gvrow = gvRefDetail.SelectedRow;
int id = Convert.ToInt32(gvrow.Cells[1].Text);
string delref = "delete from tbl_Refferal where ID='" + id + "' ";
con = new SqlConnection(conString);
con.Open();
SqlCommand cmd2 = new SqlCommand(delref, con);
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
}
Now, my question is when I select a one or more rows from gridview and select the delete option from dropdownlist, the selected rows must get deleted.
How can I do this?
Code On ddlaction_SelectedIndexChanged and stringVariableContainCheckboxvalues is string variable fetch from gridview checkbox selected in format ('1,3,5,6')
if (ddlaction.SelectedValue == "1")
{
string delref = "delete from tbl_Refferal where ID in (#checkboxSelectedValues)";
con = new SqlConnection(conString);
SqlCommand cmd2 = new SqlCommand(delref, con);
cmd2.Parameters.AddWithValue("#checkboxSelectedValues", stringVariableContainCheckboxvalues);
con.Open();
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
Fetch Multiple Checkbox values:
foreach (GridViewRow row in gvRefDetail.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb != null && cb.Checked)
{
// fetch values in string
}
}

Resources