I have the following code that is in my formViewModel to be passed to my View.
var ownerValues = aspnet_Users
.OrderBy(u => u.Surname)
.Select(u => new KeyValuePair<int, string>(u.UserId, u.Surname + " " + u.Forename.ToString() + " [" + u.UserName.ToString() + "]"));
this.OwnersList = new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);
When I run the view in explorer my drop list defaults to the first item and I want it to default to a blank row.
So my plan is to insert a initial row with userId = null and then an empty string instead of 'please select' or something similar.
Can anyone please advise me on how to do this on one line of code I think, not sure where to start.
thanks
When Rendering your SelectList you can do something like
<%:Html.DropDownListFor(x => x.ApprovalType, Model.ApprovalTypes,"")%>
if you want strongly typed list or you can try
<%:Html.DropDownList("ApprovalType", Model.ApprovalTypes, "") %>
in both examples Model.ApprovalTypes contains a SelectList or List of SelectListItems. Empty string parameter at the end is optional label and its value is also an empty string
Edit Inserting label (empty string or something else) with some value will also create problems when you try to validate it using data annotations. Selecting empty label will not trigger the error message because associate value will be -1 (not empty) as suggested in other answer.
userid cannot be null (since it's int) but if -1 works, you can try
this.OwnersList = new SelectList(new[]{new KeyValuePair<int, string>(-1, "please select")}.Union(ownerValues), "Key", "Value", incidentAction.OwnerId);
Create your own List<SelectListItem> and then do an Insert
List<SelectListItem> MyOwnerList = new List<SelectListItem>();
MyOwnerList.AddRange(new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);
MyOwnerList.Insert(0, new SelectListItem{Text = "", Value = ""});
this.OwnersList =MyOwnerList;
Related
In android studio, I want to take a value from an edit text and put it in database, when I enter another value from the edit text it will add that to the first one. like if i put 50, then i put 25, in the database it will contain 75
i am using this code to update the values in the database
public boolean addvalue(long rowId, String newAmt) {
String where = "KEY_ROWID" + "=" + rowid;
SQLiteDatabase db = myDBHelper.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(KEY_PROG, newAmt);
return db.update(DATABASE_TABLE, newValues, where, null) !=0;
}
when i try to run, the update does apply and it simply replaces the former with the latter, i am still new to android studio and sqlite please help
ContentValues objects handle only plain values.
To be able to do computations, you have to use execSQL() instead:
db.execSQL("UPDATE "+DATABASE_TABLE+
" SET "+KEY_PROG+"="+KEY_PROG+"+?"+
" WHERE "+KEY_ROWID+"=?",
new Object[]{ newAmt, rowId });
execSQL() does not return anything, so if you really need the number of updated rows, you have to use a separate query:
return DatabaseUtils.longForQuery(db, "SELECT changes()", null) > 0;
I have a gridview with a checkbox, that when selected inserts the selected items into two databases. The error occurs at a specific insert parameter that is a data type nvarchar. I'm not sure why it's giving me a boolean error. Any help would be greatly appreciated, I can post code if needed.
Okay, so let's get started. First, this has got to change from this:
sqlds1.UpdateCommand = String.Format(
"UPDATE Fees SET Inactive = '1' WHERE Description = '{0}'",
Request("cbusno"))
to this:
sqlds1.UpdateCommand = "UPDATE Fees SET Inactive = '1' WHERE Description = #Desc"
sqlds1.UpdateCommand.Parameters.AddWithValue("#Desc", Request("cbusno"))
Next, this has got to change from this:
sqlds2.UpdateCommand = String.Format(
"UPDATE OLLicenses SET lactive = '1' WHERE cbusno = '{0}'",
Request("cbusno"))
to this:
sqlds2.UpdateCommand = "UPDATE OLLicenses SET lactive = '1' WHERE cbusno = #no")
sqlds2.UpdateCommand.Parameters.AddWithValue("#no", Request("cbusno"))
Next, you'll want to use a different API here:
Sqldatasource1.Clear()
Sqldatasource1.InsertParameters.Add("cbusno", Request("cbusno"))
Sqldatasource1.InsertParameters.Add("licsubcategory", tb5.Text)
Sqldatasource1.InsertParameters.Add("description", tb5.Text)
Sqldatasource1.InsertParameters.Add("nfee", tb2.Text)
Sqldatasource1.InsertParameters.Add("lactive", "0")
Sqldatasource1.InsertParameters.Add("tadded", DateTime.Now.ToString())
Sqldatasource1.InsertParameters.Add("cuserid", Session("Username"))
Sqldatasource1.InsertParameters.Add("myfield", Request("myfield"))
Sqldatasource1.Insert()
This allows the data source to handle the typing for you.
Same as aforementioned with this block:
SqldatasourceFee.InsertParameters.Add("myfield", Request("myfield"))
SqldatasourceFee.InsertParameters.Add("Amount", tb2.Text)
SqldatasourceFee.InsertParameters.Add("CalculatorDescription", (string)clicnotxt.Table(0)(0))
SqldatasourceFee.InsertParameters.Add("Dept", "Business Tax")
SqldatasourceFee.InsertParameters.Add("Module", "Business Tax")
SqldatasourceFee.InsertParameters.Add("Type", tb4.Text)
SqldatasourceFee.InsertParameters.Add("SubType", tb5.Text)
SqldatasourceFee.InsertParameters.Add("Inactive", "0")
SqldatasourceFee.InsertParameters.Add("UserCreated", Session("Username"))
SqldatasourceFee.InsertParameters.Add("Description", Request("cbusno"))
SqldatasourceFee.Insert()
Now, take note to a couple of things. First, notice I casted this value to a string here (string)clicnotxt.Table(0)(0). That value was suspect to me, but I don't believe it's the source of your error. I think the issue here are stuff like this:
SqldatasourceFee.InsertParameters.Add("Inactive", "0")
I'm thinking, but can't be 100% sure, that it should be:
SqldatasourceFee.InsertParameters.Add("Inactive", "False")
Finally, when you build a SqlDataSource inline like this:
Dim sqlds1 As SqlDataSource = New SqlDataSource()
you need to wrap it in a Using because it implements IDisposable:
Using sqlds1 As SqlDataSource = New SqlDataSource()
sqlds1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("myconnectionstring").ConnectionString
sqlds1.UpdateCommand = "UPDATE Fees SET Inactive = '1' WHERE Description = #Desc"
sqlds1.UpdateCommand.Parameters.AddWithValue("#Desc", Request("cbusno"))
End Using
Using ASP.NET 4.0
I am having trouble on the LINQ to get the .srvc_id to be the checked values and my query below is only populating the first check box for my object.
Code
If Not IsNothing(lbServices.SelectedItem) Then
'NEW record INSERT values from list box to table.
myServices = (From item In lbServices.Items
Where item.Selected
Select New tbl_parent_to_child With
{
.id = myServices.child_id,
----- .srvc_id is where I am stuck any help would be great. It is repeating the first selected check box.
.srvc_id = lbServices.SelectedValue,
.Active = True,
.CreateDate = DateTime.Now,
.CreateByID = SecurityMethods.GetLoginUserId(Session("AuthUser")),
.UpdateDate = DateTime.Now,
.UpdateByID = SecurityMethods.GetLoginUserId(Session("AuthUser"))
}).ToList()
For Each item In myServices
ctx.tbl_parent_to_child .Add(item)
Next
End If
Try
ctx.SaveChanges()
Catch ex As Exception
Me.Master.HandleStatusMessageEvent((New StatusMessageEventArgs("Email a screen shot of this error to the Help Desk", StatusMessageType.ErrorMsg)))
End Try
I believe you want to use the item variable, .srvc_id = CInt(item.Value)
This is similar to Listbox in asp.net not getting selected items
I'm using Firebird 2.5 and asp.net (4.5).
I'm trying to find out how to use insert ... returning, or some equivalent.
Using fbDataReader, it executes the insert OK, but I can't find anyway of accessing a returned value. Using fbDataReader.GetName(0) seems to work ok, returning the variable name in the "returning" clause. This even applies to a max() in a subselect:
..... returning (select max(userid) as newid from users)
returns the text "newid".
I can't find where, or whether, the value is available.
Using a fbDataAdaptor to fill a DataTable, the insert works OK, but data table seems empty.
Does anyone know whether this is possible, and if so, how it's done?
Thanks
EDIT
Code supplied :
strConn = ....
dbConn = New FirebirdSql.Data.FirebirdClient.FbConnection(strConn)
dbConn.Open()
MySQL = "insert into users (Firstname, Lastname) VALUES (#fname,#lname) returning userid"
FbC = New FirebirdSql.Data.FirebirdClient.FbCommand(MySQL, dbConn)
FbC.Parameters.Add("fname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Pete"
FbC.Parameters.Add("lname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Davis"
FbDataReader = FbC.ExecuteReader()
FbDataReader.Read()
TextBox1.Text = FbDataReader.GetName(0)
'TextBox1.Text = str(FbDataReader.GetInt64())
'TextBox1.Text = FbDataReader.GetString(0)
TextBox1.Text = FbDataReader.GetValue(0)
According to this thread INSERT ... RETURNING ... behaves like output parameters for the Firebird .NET provider. So you will need to add an output parameter.
So something like the code below should work:
FbParameter outParam = new FbParam("userid", FbDbType.Integer)
{
Direction = ParameterDirection.Output
};
FbC.Parameters.Add(outParam);
FbC.ExecuteNonQuery();
int? userId = outParam.Value as int?;
Iam using a dropdown list ,in that am having 4 values ,the following are my values
Uk-L1
Us-L1B
Aus-BUssness
Uk-HSMP
and here i need to choose the a particular value as a selected index ,and i did that for a exact value and in my requirement i will pass only the values after that '-' .so that i need get the value to be selected and here am using the following code to select it is not working can any one help for this.
Code:
DropList.SelectedIndex = DropList.Items.IndexOf(DropList.Items.FindByValue("L1"));
Thanks.
You could try setting the selected value:
DropDown.SelectedValue = DropDown.Items
.OfType<ListItem>()
.Where(l => l.Value.EndsWith("-L1B"))
.First()
.Value;
And if you want to check if the value exists before (the First() extension method will throw an exception if the value is not found):
var item = DropDown.Items
.OfType<ListItem>()
.Where(l => l.Value.EndsWith("-L1B"))
.FirstOrDefault();
DropDown.SelectedValue = (item != null) ? item.Value : null;