deleting a row in a table - mysql

I have a following markup on my web page:
<asp:GridView ID="GridView" runat="server"
AutoGenerateDeleteButton="True"
<Columns>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
I am trying to get the value of the text field to get the correct ID of the row that I want to be deleted, however I do not know how to exactly do it, I have tried following code:
Protected Sub GridView_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView.RowDeleting
Dim row As GridViewRow = GridView.Rows(e.RowIndex)
Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text
...
However after clicking on the delete button on the generated web page I just get error:
"Object reference not set to an instance of an object."
Visual Studio points the error to the "TryCast".
I can not find any similar examples and do not understand what is happening, if somebody has a better idea of getting that ID value that would also work?

Your lblID control certainly is a label defined by this control markup:
<asp:Label ID="lblID" runat="server" Text='<% #Eval("ID")%>'></asp:Label>
On this line you tried to cast the label control as TextBox instead of Label, so it returns Nothing and throwing NullReferenceException when accessing Text property:
Dim ID As Integer = TryCast(row.FindControl("lblID"), TextBox).Text
What do you need is cast to Label and get Text property there:
Dim ID As Integer = Convert.ToInt32(TryCast(row.FindControl("lblID"), Label).Text)
Note that Convert.ToInt32 added because Text property of a label control contains string value, hence casting to Integer is necessary. If you're not sure it will return Nothing, use Integer.TryParse instead.

Related

How to show datatable from mysql to asp.net

Here is the code i make, and plese help me to create function to show datatable when i click the button.
protected void Button1_Click(object sender, EventArgs e)
{
str = "Select count(name) as total, sum(case when status = 'DONE' then 1 else 0 end) as total_done, sum(case when status = 'PROGRESS' then 1 else 0 end) as total_progress from person where name = 'RAKA'";
cmd = new MySqlCommand(str, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tot1.Text = reader["total"].ToString();
done1.Text = reader["total_done"].ToString();
prgs1.Text = reader["total_progress"].ToString();
tb1. = reader["total"].ToString();
}
}
Ok, in most cases to display some data, you don't need a loop.
However, you do want to use say a gridview (which is table anyway - just with nice fancy and easy to use asp.net stuff wrapped around it).
So, say you have this markup:
<div style="padding:35px;width:40%">
<asp:GridView ID="GridView1" runat="server" CssClass="table">
</asp:GridView>
</div>
So, now in the code behind, to load this grid (table) up, you can use this code:
protected void Button1_Click(object sender, EventArgs e)
{
string str =
"Select count(name) as total, sum(case when status = 'DONE' then 1 else 0 end) as total_done, "
+ "sum(case when status = 'PROGRESS' then 1 else 0 end) as total_progress from person where name = 'RAKA'";
DataTable rstData = new DataTable();
using (MySqlConnection con = new MySqlConnection(Properties.Settings.Default.TEST4))
{
using (MySqlCommand cmd = new MySqlCommand(str, con))
{
con.Open();
rstData.Load(cmd.ExecuteReader());
}
}
// now send data table to grid view
GridView1.DataSource = rstData;
GridView1.DataBind();
}
So, you want using System.Data - that is the basic table and rows and operations. That part (ado.net) is the basic objects you need. You then adopt your "provider".
for exmaple, I don't have MySQL installed, but I using sql server. So ONLY the provider part need be change.
So with above markup, I can fill out the gridview like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT * FROM Fighers";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And I now see/get this on the page:
but, often I will use the wizards to create the grid, and then REMOVE the data source on teh page, and use my above code. (I use the wizrard to setup the grid view, since I am lazy.
But, lets tweak up the gird. I don't want "ID", and the path name to the image, lets drop in a iamge control.
So, my markup now becomes this:
<div style="padding:35px;width:50%">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" width="150px"
ImageUrl = '<%# Eval("ImagePath") %>' /> />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code can be as before.
So, I added a image control to the grid, and a button.
So now we see/get this:
Again, note how we did NOT use a loop. But we fill out a table, and then send that table to the grid view.
And the above idea quite much applies to any kind of repeating data.
So, you can use repeater, a Gridview, listview, datalist view etc. You can feed such controls "repeating" data, and thus no need for some loop to try and fill out controls. (and if you need repeating data, then how do you add more controls to the page - that's too hard. So, use the data aware controls, and they will render that type of data for you, especially for repeating types of data.

Cant set asp.net drop down list selected value from code behind

I have inherited a web site that I have to update but I am having problems with a drop down list.
There are two asp.net drop down list boxes on a page. They are ddlReminderUser1 and ddlReminderUser2. When the page loads a function pulls data from a SQL DB and sets some hidden field values. Based on these values the drop down lists are being set.
The problem is that there are two drop down lists and only one is setting the selected value, the other is not.
Here is HTML for the drop drown lists:
<asp:DropDownList runat="server" ID="ddlReminderUser1" AutoPostBack="true" CssClass="text-primary mt-1 width125" Visible="false" OnSelectedIndexChanged="ddlReminderUser1_SelectedIndexChanged"></asp:DropDownList>
<asp:ImageButton ID="btnXUser1" runat="server" AlternateText="X" ImageUrl="~/Images/red-x-md15x15.png" ToolTip="Click to remove user 1" Visible="false" />
<br />
<asp:DropDownList runat="server" ID="ddlReminderUser2" AutoPostBack="true" CssClass="text-primary mt-1 width125" Visible="false" OnSelectedIndexChanged="ddlReminderUser2_SelectedIndexChanged"></asp:DropDownList>
<asp:ImageButton ID="btnXUser2" runat="server" AlternateText="X" ImageUrl="~/Images/red-x-md15x15.png" ToolTip="Click to remove user 2" Visible="false" />
And here is the code behind (in VB):
'Set user names in ddl's
With ddlReminderUser1
.Visible = True
If getAdList(1) < 1 Then
message = "Can't get user list from AD for Notifications.\nError: SQL104\nPlease contact the Help Desk for support."
alertMessage(message)
.SelectedIndex = 0
Else
.SelectedValue = hUser1.Value.ToString()
btnXUser1.Visible = True
End If
End With
'Check for second email address
If ddlNumberOfUsers.SelectedIndex = 2 Then
ddlReminderUser2.Visible = True
If getAdList(2) < 1 Then
message = "Can't get user list from AD for Notifications.\nError: SQL104\nPlease contact the Help Desk for support."
alertMessage(message)
ddlReminderUser2.SelectedIndex = 0
Else
ddlReminderUser2.SelectedValue = hUser2.Value.ToString()
btnXUser2.Visible = True
End If
'With ddlReminderUser2
' .Visible = True
' If getAdList(2) < 1 Then
' message = "Can't get user list from AD for Notifications.\nError: SQL104\nPlease contact the Help Desk for support."
' alertMessage(message)
' .SelectedIndex = 0
' Else
' .SelectedValue = hUser2.Value.ToString()
' btnXUser2.Visible = True
' End If
'End With
End If
The commented out section gets the exact same result. I though maybe the With statement my be the problem but it doesn't seem to be.
The function getAdList is working fine because when I check the drop down list it has the list of AD names in it.
This is what I am getting:
The drop down list that says select user should be displaying the second name, which I verified is in the DB and the hidden field value correctly. What am I missing? I have been staring at this section of code now for a few hours and nothing I do works.
Anyone have an idea?
And thanks in advance...
This is how I finally figured it out.
I changed both of the drop down list boxes to .SelectedItem.Text = [What Ever Variable] and it now works great.

Entering data using VBA in to a HTML5 site

Hi i need to enter a car reg into the below input box:
<input type="text" class="form-control text-uppercase car-registration__input ng-pristine ng-invalid ng-invalid-required ng-valid-maxlength ng-touched"
data-ng-model-options="{updateOn: 'blur'}"
data-ng-keyup="inputChange=true; regnumberNotFound=false; carLookupButtonSubmitted=false" data-motor-regnumber=""
data-msm-answer-store-key="" data-ng-required="true"
data-msm-answer-store-action="{'regnumberUpdate': {'targets': [{}]}}"
data-msm-error-tracking-view-change="" id="regnumber" name="regnumber"
data-ng-model="regnumber" maxlength="10" data-msm-field-interaction-events="click"
data-ng-change="returnedUserCheck()" required="required">
using the following i can enter the value but the box doesn't think that there is anything there and therefore wont validate and i have to manually click inot the text box:
IE.document.all("regnumber")(1).innerText = Reg
IE.document.all("regnumber")(1).setCapture
IE.document.all("regnumber")(1).Click
IE.document.all("regnumber")(1).releaseCapture
IE.document.getElementsByTagName("BUTTON")(7).Click
Any help would be greatly appreciated
Try replacing:
IE.document.all("regnumber")(1).innerText = Reg
With:
IE.document.all("regnumber")(1).value = Reg
The value attribute specifies the value of an <input> element
The value attribute is used differently for different input types:
For "button", "reset", and "submit" - it defines the text on the
button
For "text", "password", and "hidden" - it defines the initial
(default) value of the input field
For "checkbox", "radio", "image" -
it defines the value associated with the input (this is also the value
that is sent on submit)
Note: The value attribute cannot be used with <input type="file">.
Edit:
It looks as if it's using angular to check the value has changed.
Specifically, this attribute on the input element:
data-ng-keyup="inputChange=true; regnumberNotFound=false; carLookupButtonSubmitted=false"
It appears that you would need to also trigger a keyup event, which will likely require something like the following:
IE.document.all("regnumber")(1).Focus()
IE.document.all("regnumber")(1).Value = Reg + "." 'extra full stop will be removed on the next line
SendKeys "{BS}"
However, SendKeys is usually frowned upon unless absolutely necessary.
It may be worth trying to "trick" the form to recognise the value change by forcing the blur event to occur.
This can be done by setting the focus to the input box, then setting the focus to another element, as follows:
IE.document.all("regnumber")(1).Focus()
IE.document.all("regnumber")(1).innerText = Reg
IE.document.getElementsByTagName("BUTTON")(7).Focus()
IE.document.getElementsByTagName("BUTTON")(7).Click
I'd recommend trying this suggestion before going down the SendKeys route
I was having similar trouble with a form and I found this:
VBA interaction with internet explorer
Which helped me solve the exact same type of problem!
The trick was to use
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
At the top of the Module, then modify your code to the following:
Dim HWNDSrc As Long
HWNDSrc = ie.HWND
SetForegroundWindow HWNDSrc
IE.document.all("regnumber")(1).Focus()
IE.document.all("regnumber")(1).Value = Reg + "." 'extra full stop will be removed on the next line
Application.SendKeys "{BS}"

Referencing unchecked checkboxes with vbscript causes an error

I am running into a problem with my vbscript code. My HTML code looks like this
<input type='checkbox' name='DisplayRow' id='DisplayRow1' />
<input type='checkbox' name='DisplayRow' id='DisplayRow2' />
<input type='checkbox' name='DisplayRow' id='DisplayRow3' />
This is done because above there is another checkbox that calls a javascript function that will check or uncheck all of the "DisplayRow" checkboxes. The javascript function uses getElementsByName to return all of the checkboxes named "DisplayRow".
When the form's submit button is clicked the action sends it to an ASP page (classic ASP) that grabs all of the objects on the calling form by using the Request.Form command. The Request.Form command looks at the "name" attribute, not the "id" attribute of the object.
This seems to be working fine for all of the other form objects. When it gets to the checkboxes because the "name" attribute uses the same name for all of the check boxes it returns an array. The individual checkboxes can be accessed like this:
Request.Form("DisplayRow")(x)
Where x references the individual checkbox in the array.
If the checkboxes are checked I can loop through the array without any problems. If 1 or more or all of the checkboxes are unchecked then when the code references the first checkbox in the array that is unchecked the page crashes. Nothing is executed after the Request.Form command fails.
I have tried enclosing the Request.Form("DisplayRow")(x) in an IsNull function in an If statement but it still takes the program down.
Has anyone else ran into this and found a work around?
Edit
For some reason stackoverflow is not letting me add more than one comment.
#Cory. Thanks for the information
#jwatts1980. Count works but it does not let me know which of the checkboxes are checked. If the count is greater than 0 I can loop through them but if the first one is unchecked I am right back where I started with a crashed page.
You cannot do it this way because unchecked checkboxes will not be submitted in the post, only the checked ones.
I would approach this differently:
First I would add a value attribute to the checkboxes, as so:
<input type='checkbox' name='DisplayRow' id='DisplayRow1' value="1" />
<input type='checkbox' name='DisplayRow' id='DisplayRow2' value="2" />
<input type='checkbox' name='DisplayRow' id='DisplayRow3' value="3" />
Notice the value is the same as the index, this will be needed in the code.
Next I would use .Split() to gather the checkboxes selected in an array, since the values will come in as a string separated by comma, ie: 1,2,3 to your .Form() value.
Rows = Request.Form("DisplayRow")
'check if any are selected first
If Rows <> "" Then
'make an array with each value selected
aRows = Split(Rows,",")
'loop through your array and do what you want
For i = lBound(aRows) to uBound(aRows)
Response.Write "DisplayRow" & aRows(i) & " was Selected."
Next
End If
This way you only process the results for the one's selected, and ignore the others.
I've always found this essential for my library...
'GetPostData
' Obtains the specified data item from the previous form get or post.
'Usage:
' thisData = GetPostData("itemName", "Alternative Value")
'Parameters:
' dataItem (string) - The data item name that is required.
' nullValue (variant) - What should be returned if there is no value.
'Description:
' This function will obtain the form data irrespective of type (i.e. whether it's a post or a get).
'Revision info:
' v0.1.2 - Inherent bug caused empty values not to be recognised.
' v0.1.1 - Converted the dataItem to a string just in case.
function GetPostData(dataItem, nullVal)
dim rV
'Check the form object to see if it contains any data...
if request.Form = "" then
if request.QueryString = "" then
rV = nullVal
else
if request.QueryString(CStr(dataItem))="" then
rV = CStr(nullVal)
else
rV = request.QueryString(CStr(dataItem))
end if
end if
else
if request.Form(CStr(dataItem)) = "" then
rV = CStr(nullVal)
else
rV = request.Form(CStr(dataItem))
end if
end if
'Return the value...
GetPostData = rV
end function
To use the function you simply pass in the form or query string item you're looking for and what to replace empty values with...
Dim x
x = GetPostData("chkFirstOne", false)
You can keep using your existing code by adding a single condition:
If Request.Form("DisplayRow").Count > 0 Then
'your code here
Else
'consider adding message saying nothing was selected
End If

AdvancedDataGrid: dataTip = headerText

I have a pretty straightforward question which google fails to give me the answer to :
I have an AdvancedDataGrid where i build the columns dynamically (variable number of columns) in ActionScript, and i want the dataTip to display the column headerText when the user hovers over a cell. Adobe's example dataTipFunction:
private function tipFunc(value:Object):String
{
if (value is AdvancedDataGridColumn)
return "Column Name";
// Use the 'name' property of the data provider element.
return "Name: " + value["name"];
}
But in this case the value is only an AdvancedDataGrid column if the user hovers over a column header? I want the dataTip to always show the headerText for that column. So if i have to use this function, then how do i get the column headerText for a cell?
And as i understand the dataTipField i can't really use it to statically equal column.headerText (dataTipField = headerText).
Anyone have any pointers on how i can achieve this? It seems like a really easy task, still i can't seem to find out how :)
You can use a different function per column, which could be anonymous:
<AdvancedDataGridColumn dataTipFunction="{function(value:Object):String{return 'Data Tip'}}" ... />