Combobox first values should be null - c#

Using C# & MYSQL
Using Combobox in my webpage, in a combobox i want to display a null values first, then it should display all values..
For Example
Combobox.item = null values
combobox.item = 1
Combobox.item = 2
....,
Code
cmd = new OdbcCommand("Select vehicleno as vehicleno from tb_car", con);
ada = new OdbcDataAdapter(cmd);
ada.Fill(data1);
cmbvnoview.DataValueField = "vehicleno";
cmbvnoview.DataSource = data1;
cmbvnoview.DataBind();
Above code is working, but is displaying all the values, first it should display a null value, then it should display all the values.
How to modify my code....
Need Code Help

Try this after you data bind
...
cmbvnoview.DataBind();
cmbvnoview.Items.Insert(0, new ListItem("Null Values", "-1"));
Change -1 with whatever you feel confortable with. You will have to change your sql to filter out nulls.
OR
try this
cmd = new OdbcCommand("Select IFNULL(vehicleno, 'Null Values')
as vehicleno from tb_car", con);
Your question does not quite make sense so this may not be the right answer.

Just prefix an empty/dummy entry to you datasource.

To keep the logic at one place, just add a null record to your sql statement
cmd = new OdbcCommand("Select null as vehicleno Union Select vehicleno as vehicleno from tb_car", con);

Related

Combine two data fields(columns) values and display in Listbox-ASP.Net?

I want to select data from Microsoft SQL Server and concatenate two of its column values and display it in ListBox.
For example - there are two columns in SQL, namely Software name and Software-users. A single software has N number of users what I want to do is select the software name in SQL and concatenate it with Software users name and display it in the listbox.
So far I tried this, but the listbox displays null.
SqlCommand cmd = new SqlCommand("Select [SWName] +'-'+ [SWUser] as Creator from AllSWUsers WHERE SWName = #SWName", con);
cmd.Parameters.AddWithValue("#SWName", Global.usrlsts);
SqlDataAdapter daFill = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
daFill.Fill(ds);
lstUsers.DataSource = ds;
lstUsers.DataTextField = "Creator";
lstUsers.DataValueField = "SWName";
lstUsers.DataBind();
It may be the reason you are not selecting SWName in your query but you are using that column as shown below in your code.
lstUsers.DataValueField = "SWName";
Try this
Select ISNULL([SWName], '') as [SWName], ISNULL([SWName],'') +'-'+ ISNULL([SWUser], '') as Creator from AllSWUsers WHERE SWName = #SWName

Can't update MS Access database in C#?

My code:
OleDbCommand cmd1 = new OleDbCommand("UPDATE student_info SET fee_due = #fee_due WHERE adm_no = #adm_no", con);
cmd1.Parameters.AddWithValue("#adm_no", adm_no);
cmd1.Parameters.AddWithValue("#fee_due", fee_due);
int affect = cmd1.ExecuteNonQuery();
MessageBox.Show(affect.ToString());
My code always shows 0 row affected every time but in my database the are must be a row that will be affect
Can you suggest me how I debug this problem?
Since OleDB for MS Access doesn't support named parameters (only positional parameters), you must be very careful about providing the values in the same order in which you define the parameters.
In your case, the statement lists #fee_due first, before #adm_no - but you provide the values in the other order.
Change your code like this:
OleDbCommand cmd1 = new OleDbCommand("UPDATE student_info SET fee_due = #fee_due WHERE adm_no = #adm_no", con);
// provide the value for #fee_due FIRST
cmd1.Parameters.AddWithValue("#fee_due", fee_due);
// provide the value for #adm_no only after #fee_due
cmd1.Parameters.AddWithValue("#adm_no", adm_no);
int affect = cmd1.ExecuteNonQuery();
MessageBox.Show(affect.ToString());

C# - How to use variable from dropdown in SQL query, and add column to second dropdown

I am trying to write a query that pulls a column from a table, and then outputs to a dropdown list. I was using a long string of if else statements, but this does not accomplish my goal of being able to add another column to the table (which was added already) without adding another else clause to the lookup.
I have two dropdowns. The second one needs to change based on the first one's selection. Both drop downs are using separate tables so I can name the columns in the second table the same as a string in one of the columns of the first table. The items selected in the first dropdown have the same name as the columns in the second table for the second dropdown.
I am using Visual Studio 2015 with SQL 2012.
Here is the code I have now, I have been trying parameters but I just can't quite get it to work, it is saying that the variable is not in the table. I know [systemItem] is not the best way to actually run it, I edited it so you can see what I am trying to do. The ORDER BY is in there to eliminate blank spaces from showing in the dropdown (which worked fine in the massive list of if else's). Thanks in advance guys!
systemItem = firstDropdown.Text;
secondDropdown.Items.Clear();
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30");
conn.Open();
SqlCommand cm = new SqlCommand("SELECT [systemItem] FROM [table] WHERE [systemItem]IS NOT NULL ORDER BY [systemItem] ASC AND [systemItem] =#sItem", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "#sItem";
param.Value = systemItem;
cm.Parameters.Add(param);
{
SqlDataAdapter da = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
secondDropdown.Items.Add(dr[sItem]);
secondDropdown.SelectedIndex = 0;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
Edit: fixed name of one of the dropdowns to reflect what I am clearing.

How to set dropdown list value and item as database table value in edit?

When I click edit button the form filling database values in textbox as well as dropdown list..
Textbox values is set. But I can't set dropdownlist values..
The code is;
SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string str = "Select * from Master where Id='" + id + "'";
SqlCommand command = new SqlCommand(str, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ddCustomerName.DataValueField = reader["CustomerId"].ToString();
txtPickupLocation.Text = reader["Location"].ToString();
}
con.Close();
you have to make the CustomerId in the list selected,for that you have to write
ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected=true;
instead of
ddCustomerName.DataValueField = reader["CustomerId"].ToString();
Hey Saranya earlier post is perfect but it gives error if Dropdown values not matched with DB value or if Dropdown havn't value which is return by Db ,So Safer side always checks null value also.
Please Use this code
if (ddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()) != null)
dddCustomerName.Items.FindByValue(reader["CustomerId"].ToString()).selected = true;
use selectedvalue property
while (reader.Read())
{
ddCustomerName.SelectedValue= reader["CustomerId"].ToString();
txtPickupLocation.Text = reader["Location"].ToString();
}

Need sql for creating view set in asp.net c#

I am using sqlconnection. I want to create a view and select from the view set.
Like I have shown below I have created a view called vwtopic.. from this I need to select distinct values of a column.
I cannot put in one easy statment because i need distinct values of topic column only and need to order by another column datetime..
So I am first creating a view where I am ordering by datetime and from this I am selecting distinct topic.
Problem is I am able to create a view set, but from this I am not able to select the distinct topic data to a SqlDataAdapter.. I frankly dont know the syntax.. I have not tried this before..
First part:
SqlConnection con = new SqlConnection("server=xxxx;database=wbsd;user id=***;password=***;");
SqlCommand add = new SqlCommand("CREATE VIEW vwtopic AS SELECT * FROM sr_topic_comment ORDER BY datetime DESC", con);
try
{
add.Connection.Open();
add.ExecuteNonQuery();
add.Connection.Close();
}
catch (System.FormatException)
{
}
Second part:
String sqlcmd = "SELECT DISTINCT topic FROM vwtopic WHERE owner='" + owner + "'";
SqlDataAdapter adap = new SqlDataAdapter(sqlcmd,con);
Instead of creating Views in Code, use the "WITH" statement or Sub-queries this should meets your needs:
WITH [vwtopic] AS (
SELECT * -- I recommend using each column name
FROM [sr_topic_comment]
-- not sure if ORDER BY is allowed here:
-- ORDER BY [datetime] DESC
)
SELECT DISTINCT [topic] FROM [vwtopic] -- add WHERE, ORDER BY
Since the view you are creating does not have any filters defined, selecting distinct values from the view is equivalent to selecting distinct values from the table. When selecting distinct values, you can only order by those values (not the datetime column as you're attempting here). Therefore, you can do:
SqlCommand cmd = new SqlCommand("SELECT DISTINCT topic FROM sr_topic_comment WHERE owner = #owner", con);
cmd.Parameters.Add(new SqlParameter(#owner, SqlDbType.Varchar, 25));
cmd.Parameters["#owner"].Value = owner;
DataSet ds = new DataSet();
using (SqlDataAdapter adap = new SqlDataAdapter(cmd)) {
adap.Fill(ds);
}
This will give you a DataSet filled with the distinct values from the table that meet the filter criteria (owner == the supplied owner).
I found the answer below will do the trick for me...
I am filling the result in dataset and calling my required column 'topic'..
SELECT DISTINCT topic,datetime FROM sr_topic_comment WHERE owner='sr' ORDER BY datetime DESC
Thank you very much for your inputs.. I learnt about WITH clause today.. cheers..

Categories