Insert into ASPxGridView with Cascading DropDowns - devexpress

I am using DevExpress Gridview for making CRUD operations,
I am following this link. And Update operation working fine.
I want to Insert new rows, So I added properties in Gridview, And it shows create button.
The problem is, In new row, When I change country it's not updating City automatically. It is calling JavaScript function after changing Country dropdown, But not calling C# code function.
Below is my grid code,
<dx:ASPxGridView AutoGenerateColumns="false"
ClientSideEvents-Init="OnInit"
DataSourceID="dsMasterDataList"
ClientInstanceName="gvMasterDataList"
ID="gvMasterDataList"
KeyFieldName="ID"
OnBatchUpdate="GvMasterDataList_BatchUpdate"
OnCellEditorInitialize="gvMasterDataList_CellEditorInitialize"
OnCommandButtonInitialize="gvMasterDataList_CommandButtonInitialize"
OnRowDeleted="gvMasterDataList_RowDeleted"
OnRowInserted="gvMasterDataList_RowInserted"
OnRowUpdated="gvMasterDataList_RowUpdated"
OnRowValidating="gvMasterDataList_RowValidating"
OnSummaryDisplayText="gvMasterDataList_SummaryDisplayText"
runat="server" >
<SettingsEditing Mode="Inline" />
<Columns>
<dx:GridViewCommandColumn ButtonType="Image" Caption=" " FixedStyle="Left" ShowClearFilterButton="true" ShowDeleteButton="true" ShowNewButtonInHeader="true" Width="32" />
<dx:GridViewCommandColumn ShowEditButton="true" Caption=" " ShowClearFilterButton="true" />
<dx:GridViewDataTextColumn FieldName="ID" Visible="false" />
..
..
Where I need to change to make it work?

The main idea is to omit the following conditions inside the "grid_CellEditorInitialize" event handler:
CS:
//if(!grid.IsEditing || e.Column.FieldName != "City") return;
//if(e.KeyValue == DBNull.Value || e.KeyValue == null) return;
VB:
'If (Not grid.IsEditing) OrElse e.Column.FieldName <> "City" Then
' Return
'End If
'If e.KeyValue Is DBNull.Value OrElse e.KeyValue Is Nothing Then
' Return
'End If
They are always true for a "New" mode and skip the rest code logic.
Check out a self-contained db-independent solution at E3689 instead.

Related

Object reference not set to an instance of an object for Gridview Delete Button [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am currently trying to get my button working in my Visual Studio Page.
I am running some code in my page an it keeps returning this error:
Object reference not set to an instance of an object. Description: An
unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code. Exception Details:
System.NullReferenceException: Object reference not set to an instance
of an object.
Line 466: Delete.OnClientClick =
String.Format("Javascript:HiddenPopup('deletePopup', {0}');", Cell2)
Source File:
\BATMAN\Sales\Transfer\Website\QuotemanDJ3\Production\PlantAndMaintenance.aspx.vb
Line: 466
I have looked at lots of solutions online but i still cant seem to figure out what I am refrencing wrong, If I could get some assistance with this it would be much appreciated.
This is my VB code:
Protected Sub Service_History0_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles Service_History0.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'-----------------------------------------------------------------
Dim pdfExtention2, wordExtention2, excelExtention2 As ImageButton
pdfExtention2 = e.Row.FindControl("PdfExtention2")
wordExtention2 = e.Row.FindControl("WordExtention2")
excelExtention2 = e.Row.FindControl("ExcelExtention2")
If e.Row.DataItem("Extention").ToString = "application/pdf" Then
pdfExtention2.Visible = True
ElseIf e.Row.DataItem("Extention").ToString = "application/msword" Then
wordExtention2.Visible = True
ElseIf e.Row.DataItem("Extention").ToString = "application/vnd.ms-excel" Then
excelExtention2.Visible = True
End If
'-----------------------------------------------------------------
Dim ImgBtn As New ImageButton
ImgBtn = e.Row.FindControl("PdfExtention2")
ImgBtn.Attributes.Add("onClick", "javascript:window.open('DisplayPM.aspx?ServiceID=" + Service_History0.DataKeys(e.Row.RowIndex).Value.ToString + "');")
Dim ImgBtn2 As New ImageButton
ImgBtn2 = e.Row.FindControl("WordExtention2")
ImgBtn2.Attributes.Add("onClick", "javascript:window.open('DisplayPM.aspx?ServiceID=" + Service_History0.DataKeys(e.Row.RowIndex).Value.ToString + "');")
Dim ImgBtn3 As New ImageButton
ImgBtn3 = e.Row.FindControl("ExcelExtention2")
ImgBtn3.Attributes.Add("onClick", "javascript:window.open('DisplayPM.aspx?ServiceID=" + Service_History0.DataKeys(e.Row.RowIndex).Value.ToString + "');")
'-----------------------------------------------------------------
Dim Cell2 As String
Cell2 = GridView1.DataKeys(e.Row.RowIndex).Values("ServiceID").ToString
Dim Delete As Button
Delete = e.Row.FindControl("DeleteInduction")
Delete.OnClientClick = String.Format("Javascript:HiddenPopup('deletePopup', '{0}');", Cell2)
connection.Close()
'-----------------------------------------------------------------
End If
End Sub
This is my Markup Code for my gridview (My button is inside my gridview):
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource7" DataKeyNames="ServiceID,ID" >
<AlternatingRowStyle BackColor="#CCFFFF" >
</AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Serial No" HeaderText="Serial No" SortExpression="Serial No" />
<asp:BoundField DataField="Record Type" HeaderText="Record Type"
SortExpression="Record Type" Visible="False" >
</asp:BoundField>
<asp:BoundField DataField="ServiceID" HeaderText="ServiceID"
SortExpression="ServiceID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"
Visible="False" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageURL="~/icons/pdf.gif">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate><asp:Button runat="server" Text="Delete" ID="DeleteInduction" />
<asp:ModalPopupExtender ID="DeleteInduction_ModalPopupExtender" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="cancelButton"
DynamicServicePath="" Enabled="True" PopupControlID="deletePopup"
TargetControlID="DeleteInduction" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Some guidance with this would be appreciated, Thankyou in advance.
Consider your code here:
Delete = e.Row.FindControl("DeleteInduction")
Delete.OnClientClick = String.Format("Javascript:HiddenPopup('deletePopup', '{0}');", Cell2)
FindControl() returns null if it doesn't find the control. When that happens, the immediate next line will throw that exception because you can't reference a property (OnClientClick) from null.
You can prevent the error simply by checking if the result is null:
Delete = e.Row.FindControl("DeleteInduction")
if (Delete != null)
Delete.OnClientClick = String.Format("Javascript:HiddenPopup('deletePopup', '{0}');", Cell2)
Then the question becomes, what do you want to do when it is null? Anything at all? The above code will just silently ignore it. Do you instead want to do something else? That's where you'd do it:
Delete = e.Row.FindControl("DeleteInduction")
if (Delete != null)
Delete.OnClientClick = String.Format("Javascript:HiddenPopup('deletePopup', '{0}');", Cell2)
else
{
// handle the case where DeleteInduction wasn't found.
}
Keep in mind, for example, that some events in controls don't always apply to data-bound rows. Depending on the event which contains this code, you could also be processing the code on header and/or footer rows which wouldn't contain the DeleteInduction control. In those cases you'd likely want to just ignore the code entirely.
For example in a GridView you can check the row type before executing your logic:
if (e.Row.RowType == DataControlRowType.DataRow)
{
// put your row logic here
}

set the value of inputbox inside a data grid through VB code

I have a asp datagrid one of the column is having one input
<asp:DataGrid ID="dgItem" runat="server" Width="100%" CssClass="TableList" AutoGenerateColumns="False" PagerStyle-Visible="False">
<Columns>
<asp:TemplateColumn HeaderText="Disc %">
<HeaderStyle HorizontalAlign="Right" CssClass="ListHeader"></HeaderStyle>
<ItemStyle HorizontalAlign="Right" Width="6%" CssClass="TdList"></ItemStyle>
<ItemTemplate>
<input class="Input" onkeypress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode != 46 && event.keyCode != 45) event.returnValue=false;"
id="txtDiscRate" style="width: 100%; text-align: right" value="0.00" name="txtDiscRate"
runat="server" onchange="checkrate();">
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle Visible="False"></PagerStyle>
</asp:DataGrid>
how to set the value of that column through VB.net code
This column is the 10th cell. In the 1st cell there is a value which should be set to the 10th column
So, I've tried the following..but not working.
Dim lnDiscRate As Double
Double.TryParse(lodgGrid.Cells(1).Text, lnDiscRate)
Dim loDiscRate As HtmlInputText
For Each lodgGrid In dgItem.Items
loDiscRate = lodgGrid.Cells(10).FindControl("txtDiscRate")
loDiscRate.Value = lnDiscRate 'Not working :(
loDiscRate.Enabled = True 'this is Working..
Next
Pls Help!!
Got something else. when i do this
CType(lodgGrid.FindControl("txtDiscRate"), HtmlInputText).Value = 10 ' Working
CType(lodgGrid.FindControl("txtDiscRate"), HtmlInputText).Value = lnDiscRate ' Not Working
Implement ItemDataBound on your DataGrid and use the following
Private Sub dgItem_ItemDataBound(sender As Object, e As DataGridItemEventArgs) Handles dgItem.ItemDataBound
'Get the text value of the second cell as stated above, if you want the first use 0
Dim lnDiscRate As String
lnDiscRate = e.Item.Cells(1).Text
'set the text value of the desired input to the string found above...
CType(e.Item.FindControl("txtDiscRate"), HtmlInputText).Value = lnDiscRate
End Sub

How to handle OnRowClick event of ASPxGridView in code behind?

I am using ASP.Net with VB to display records in a grid view.
In a normal ASP GridView, I can simply handle SelectedIndexChanged Event from code behind like this:
Sub mySub(ByVal sender as Object, ByVal e As EventArgs)
Handles GridView1.SelectedIndexChanged
Dim id as String = GridView1.SelectedRow.Item(0).ToString
Response.Redirect("Customer.aspx?ID=" & id) 'Or Whatever
End Sub
Now I am trying to do the same but with ASPxGridView that comes with DevExpress. Obviosly, there is no built in Event that can be handled directly from code behind. I have to go through client click with javascript, which I don't mind to but all my attempts to pass the click event from the client to the server code behind failed.
Here is my ASP page
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
KeyFieldName="id" Width="550px" OnSelectionChanged="row_selected" >
<SettingsBehavior AllowFocusedRow="True" />
<SettingsText Title="Customers" />
<Columns>
<dx:GridViewDataTextColumn FieldName="id" ReadOnly="True" VisibleIndex="1">
<EditFormSettings Visible="False" />
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="2">
</dx:GridViewDataTextColumn>
</Columns>
<Settings ShowTitlePanel="True" />
<ClientSideEvents FocusedRowChanged="function(s, e) {
row_selected();
}" />
</dx:ASPxGridView>
And here is my code behind (Which never gets called)
Sub row_selected()
Dim id as String = ASPxGridView1.SelectedRow.Item(0).ToString
Response.Redirect("Customers.aspx?ID=" & id)
End Sub
How can I call a function from code behind by clicking on a row on ASPxGridView row?
Try this:
1. Set ASPxGridView1.SettingsBehavior.ProcessFocusedRowChangedOnServer to true.
2. Handle server side FocusedRowChanged event
This will do what you want..
In my case,
I want to get contents of a field ('ID') from ASPxGridView when the user clicks on the row...
Create the ClientSideEvent for row click and put "RowClick(s, e);" in the function.
Create the actual function the event will call as shown below - and here is the tricky part;
do not use GetFocusedRowIndex() to get the index because it is the FOCUSED index.
Use e.visibleIndex
function RowClick(s, e) {
// Do callback to get the row data for 'ID' using current row.
MyAspxGridView.GetRowValues(e.visibleIndex, 'ID', OnGetRowId);
}
Create your call back to get the field you want. I'm getting 'ID'.
function OnGetRowId(idValue) {
alert('ID: ' + idValue.toString());
}

Calling Data From GridView

I have a GridView with a bunch of DynamicFields like so;
<asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource">
<Columns>
<asp:DynamicField HeaderText="Date Submitted" DataField="DATE_CREATED" />
<asp:DynamicField HeaderText="Assigned To" DataField="ASSIGNED_TO" />
<asp:DynamicField HeaderText="Active Account" DataField="Active_Account" />
<asp:DynamicField HeaderText="Client ID" DataField="CLIENT_ID" />
<asp:DynamicField HeaderText="Client Type" DataField="CLIENT_Type" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="GridDataSource" OnSelected="TotalRows" runat="server"
EnableDelete="true">
<WhereParameters>
<asp:DynamicControlParameter ControlID="FilterRepeater" />
</WhereParameters>
</asp:EntityDataSource>
Now it displays fine, the right data comes to screen but when I try to access that data using a row number I'm always finding blank cells. For example I tried the following to check every cell but to no avail;
Dim x As Integer = 0
Dim y As Integer = 0
While x < GridView1.Rows.Count
While y < GridView1.Rows(x).Cells.Count
If Not (GridView1.Rows(x).Cells(y).Text = "") Then
MsgBox(String.Format("{0},{1},{2}", x.ToString, y.ToString,
GridView1.Rows(x).Cells(y).Text))
End If
y = y + 1
End While
x = x + 1
y = 0
End While
No message box displayed so all the cells are empty strings. But I can clearly see they're populated on screen! What am I doing wrong?
UPDATE
After Pilgerstorfer Franz suggestion that I look for Textbox elements I used the following code which basically looks at all the cells in the table and try's to pull data out of them and if it's not blank then display a msgbox (also informs me of any new controls I haven't accounted for);
If GridView1.Rows(0).RowType = DataControlRowType.DataRow Then
For r = 0 To GridView1.Rows.Count - 1
For c = 0 To (GridView1.Rows(r).Cells.Count - 1)
Dim cell = GridView1.Rows(r).Cells(c)
For b = 0 To cell.Controls.Count - 1
If (cell.Controls(b).GetType() Is GetType(TextBox)) Then
Dim td = CType(cell.Controls(b), TextBox)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(LiteralControl)) Then
Dim td = CType(cell.Controls(b), LiteralControl)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(DynamicControl)) Then
Dim td = CType(cell.Controls(b), DynamicControl)
Text = td.Table.Columns.Item(c).DisplayName()
Else
MsgBox(String.Format("New Control of type: {0}", cell.Controls(b).GetType().FullName))
End If
If Not Text = "" Then
MsgBox(String.Format("{0},{1},{2}", c.ToString, b.ToString, Text))
End If
Next
Next
Next
End If
Unfortunately most cells just contained DynamicControl and since I was putting the DisplayName into Text I was just getting the column header every time. So how do I get the text value property out of a DynamicControl?
Additional Info
I'm further confused by this problem because since this is a project that I'm updating there is initial code two lines of which are;
Dim UserID = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value)
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(1).ToString
These successfully bring back UserID and ClientType. Now I don't really understand DataKeys but I tried using;
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(Num).ToString
where Num increases by one every time expecting it to bring back the rest of the row data, but I simply got an index was out of range error.
ANOTHER UPDATE!!
Here is another bit of the ASPX page but I'n not entirely certain what it does. Pilgerstorfer Franz created some code to look for the textboxes created by the dynamicControl. Now I'm wondering if this code here causes other types of controls to be used rather than Textboxes. Thoughts?
<asp:FilterRepeater ID="FilterRepeater" runat="server" Visible="false">
<ItemTemplate>
<h2><asp:Label ID="lblDisplay" runat="server" Text='<%#
Eval("DisplayName") %>' AssociatedControlID="DynamicFilter$DropDownList1" /></h2>
<asp:DynamicFilter runat="server" ID="DynamicFilter"
OnSelectedIndexChanged="OnFilterSelectedIndexChanged" />
</ItemTemplate>
<FooterTemplate><br /><br /></FooterTemplate>
</asp:FilterRepeater>
According to my assumptions (see comments) I did a small demo...
<asp:DynamicDataManager ID="DynamicDataManager1" runat="server">
<DataControls>
<asp:DataControlReference ControlID="GridView1" />
</DataControls>
</asp:DynamicDataManager>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ContactID" DataSourceID="EntityDataSource1" AllowPaging="true"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:DynamicField DataField="ContactID" ReadOnly="true" HeaderText="ContactID" />
<asp:DynamicField DataField="Title" HeaderText="Title" />
<asp:DynamicField DataField="FirstName" HeaderText="FirstName" />
<asp:DynamicField DataField="LastName" HeaderText="LastName" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=dbTestIT34_EFEntities"
DefaultContainerName="dbTestIT34_EFEntities" EnableFlattening="False" EnableUpdate="True"
EntitySetName="Contacts" EntityTypeFilter="Contact">
</asp:EntityDataSource>
And according to my data storage I did handle the rowUpdating event. Unfortunatelly accessing any control within a dynamic control is not easy. So I did a very quick and dirty hack...
protected void Page_Init(object sender, EventArgs e)
{
GridView1.EnableDynamicData(typeof(Contact));
EntityDataSource1.ContextType = typeof(dbTestIT34_EFEntities);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int row = 0;
int firstNameColumn = 2;
while (row < GridView1.Rows.Count)
{
// sorry, a little bit confusing ...
// as dynamic control generates other controls dynamically,
// this was the very first thing that worked for me!
TextBox t = GridView1.Rows[row].Cells[firstNameColumn].Controls[0].Controls[0].Controls[0] as TextBox;
if (t != null)
Debug.WriteLine(t.Text);
row++;
}
}
Hope that helps!
Iterating through the controls never worked for me so in the end I gave up and just queried the DB again... Eh it works.

Hiding ItemTemplate in gridview

I have this code in .aspx page
<gridview .....
<columns>
............
...........
<asp:templatefield Visible="true" headertext="Title" >
<edititemtemplate>
<asp:checkbox id="chkTitle" runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:commandfield buttontype="Link" edittext="Edit" showeditbutton="true"/>
</columns>
</gridview>
i only want to show the column when the user clicks on Edit button to edit the row.
In your GV Data Bound Event Handler (not row data bound):
For i As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.EditIndex = -1 Then
GridView1.Rows(i).Cells(0).Visible = False
else
GridView1.Rows(i).Cells(0).Visible = true
end if
Next
If GridView1.EditIndex = -1 Then
GridView1.HeaderRow.Cells(0).Visible = False
End If
Source
Code such as GridView.Columns[9].Visible = false; should work - only thing is that grid data-bind must happen after this line. In case you are relying on the view-state for binding the grid in post-back scenarios then you may try putting GridView.DataBind() after you set the column visibility.
Yet another harder way is to set visibility at cell levels in RowDataBound event - see this article that is using this technique.

Resources