Combobox add rows dynamically and dropdown from SQL Server stored procedure - c#

This is basically a search tool. When I type some thing in a combobox, the combobox drops down and will show me suggestions (something like Google search bar)
I created a procedure which does some complex calculations, which take one parameter and returns some rows. Then I created a combobox event (On Update Text).
And in the event handler I wrote this code:
private void combobox_TextUpdate(object sender, EventArgs e)
{
this.combobox.Items.Clear();
DataTable List = new DataTable();
if (this.combobox.Text.Length > 0)
{
List = searchIt(combobox.text);
foreach (DataRow Row in List.Rows)
{
this.combobox.Items.Add(Row.ItemArray.GetValue(0).ToString());
}
this.combobox.DroppedDown = true;
}
}
static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlDataAdapter DA = new SqlDataAdapter("USE [McFarlane Industries] " +
"EXEC search " +
STR, connectionString);
DA.Fill(DT);
con.Close();
return DT;
}
The function searchIt executes the stored procedure and it returns a DataTable. The stored procedure is working fine in SQL Server Management Studio.
But in the application it is not working correctly in some cases.
When I type [space], then it throws an exception and it says stored procedure needs parameter which is not provided.
There are many other characters when I type them it throws exception that invalid character at end of string "my string".
Any suggestion how could I achieve my goal.

Call your stored procedure with sqlcommand to fill your datatable
using (SqlConnection scn = new SqlConnection(connect)
{
SqlCommand spcmd = new SqlCommand("search", scn);
spcmd.Parameters.Add("#blah", SqlDbType.VarChar, -1); //or SqlDbType.NVarChar
spcmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(spcmd))
{
da.Fill(dt);
}
}

static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlCommand command = new SqlCommand("Name_of_Your_Stored_Procedure",con);
command.CommandType=CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#parameter_name",SqlDbType.NVarChar));
command.Parameters[0].Value="Your Value in this case STR";
SqlDataAdapter DA = new SqlDataAdapter(command);
DA.Fill(DT);
con.Close();
return DT;
}
Important :
'parameter_Name' and 'Name_of_Your_Stored_Procedure' should be replaced by yours which you have in database. And value of parameter could be like "abc" (combox.Text)
Command and its type, its text are necessary.
Adding parameters depends upon your stored procedure. They can be 0,1 or more but once they are added their values must be given. conn(connection) can be passed to new SqlCmmand() or new SqlDataAdapter()
No need of things like 'use' and 'exec'
Following me and this link might be helpful in future for stored procedures
http://www.codeproject.com/Articles/15403/Calling-Stored-procedures-in-ADO-NET
Two optional Suggestions for you
use variable name 'list' instead of 'List' (you used) however you will not get problem with this name until you add a namespace using System.Collections.Generic; but you may need to use this namespace in future.
Use only list.Rows[0].ToString(); no need to get itemarray then get value when you are working with data in strings;

Related

The DataSet result is always empty in C#

I am retrieving particular column value using DataSet.
This is my code:
public DataSet GetRedirectURL(string emailId)
{
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(#"Connection_String_Here"))
{
con.Open();
SqlCommand sqlComm = new SqlCommand("usp_Login", con)
{
CommandType = CommandType.StoredProcedure
};
sqlComm.Parameters.AddWithValue("#EmailId", emailId);
SqlDataAdapter da = new SqlDataAdapter
{
SelectCommand = sqlComm
};
da.Fill(ds);
}
return ds;
}
I have also used DataTable instead of it but the same result.
I have checked my Stored Procedure and when I pass Parameter it shows Data. So, nothing wrong with the SP. But the Table doesn't show any data and is always empty as shown below:
What am I missing? Any help would be appreciated.
I'd suggest you to first evaluate the content of your DataSet. For instance, type in your Immediate Window (or add a quick watch) to check ds.Tables[0].Rows.Count. Basically, to assert your DataSet has been properly filled with the contents fetched from the database, and focus on the data assignment from the DataSet to the grid object you're using to display it.
Also, the .Fill() method has a returning object which is an int representing the amount of rows that have been successfully filled into the target object. For instance:
int result = da.Fill(ds);
Check the value of result after the .Fill() method has been executed.
Finally, I guess you're using a DataGridView object to visualize the results. If so, how are you binding data? Should be something like:
dataGridView1.DataSource = ds.Tables[0];
PS: As I've read in other comments, no, you don't need to execute the .Open() method on the connection. That's not necesarry, it's done implicitely when using the (using SqlConnection conn = SqlConnection..)

Getting data in textbox

I want to do " When I write "Item Code" on textbox and click search, It will search & found that item in sql database which has that item code . And Bring it name to textbox2(ITEM NAME). How can I do it ? I can bring it on colomn/raw but Idk how can I bring that item name on textbox2
I can search data on database and bring it to dataGridview . With this code
if (textBox1.Text.Trim() == "") errorProvider1.SetError(textBox1, "Fiil in the blanks");
else errorProvider1.SetError(textBox1, "");
conn.Open();
string regs = "SELECT * from stackTable where itemCodu=#Cod";
SqlCommand cmd = new SqlCommand(regs, conn);
cmd.Parameters.AddWithValue("#cod", textBox1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridView.DataSource = dt;
conn.Close();
---operation sequence ( Which I want to do :D )
Search on Database
If found, bring data on Textbox2
If didn't find, Error provider, message textbox
So you have a datatable, all you should have to do is to check the count after the fill with a simple if statement:
if(dt.rows.count == 0)
{
MessageBox.Show("Not Found!!");
}
else
{
textBox2.DataBindings.Add("Text", dt, "the column you want to use for textbox2");
}
You should also be using using statements so that all the objects are disposed of properly.
here's an example of how I would write what you have:
textbox2.DataBinding.Clear(); //clear the databinding so it can be added for the new data found.
using(SqlConnection conn = new SqlConnection("Your connection string here")
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * from stackTable where itemCodu=#Cod")
{
da.SelectCommand.Parameters.Add("#Cod", sqlDbType.VarChar).Value = textBox1.Text; //see comment below for this change
da.fill(dt);
if (dt.Rows.Count == 0)
{
//display not found message
}
else
{
//bind to textbox (described above)
}
}
Also note, instead of allowing the parameter to be implicitly typed, it is often better to specify the type of data the parameter should receive. This can be done by using Add instead of AddWithValue
cmd.Parameters.Add("#cod", SqlType.VarChar).Value = textBox1.Text;
The last thing to note with your code is that you can use the sqlDataAdapter without the SqlCommand.
One other thing I thought I should add:
If you know you will only ever receive 1 or 0 rows from the search, and you're not interested in binding the data, you could simply just set the textbox's .Text to the column of the row in the datatable.
For example, if you wanted to display a column in your table named Item you could simply use
textBox2.Text = dt.Rows[0]["Item"].ToString();

Sending DataTable to a stored procedure from C#

Need some help with DatagridView & DataTable.
Basically I have a DatagridView which OnLoad populates with the data from a table in SQL Server
When I click a button on UI, this DataGridView adds a new column to the front of grid "Update" which is a checkbox column
Now when the user ticks all those rows which needs updating and clicks Update...
I want to update all the rows which are ticked (for example: I wish to set the owner of these rows from Person A to Person B)
I've looked at DataTable but I'm confused
My logic is to add all the selected columns to a DataTable and send this to a stored procedure in SQL Server which would update the values.
If I'm not mistaken, I shall be sending a DataTable with just an ID column followed by From & To (owners) to the stored procedure.
Please guide me if I'm wrong, any help would be immensely appreciated.
private DataTable getDataGridID()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
foreach (DataGridViewRow row in dgTeamDashboard.Rows)
{
if (Convert.ToBoolean(row.Cells["Update"].Value) == true)
dt.Rows.Add(row.Cells["ID"].Value);
}
return dt;
}
I've now progressed upto this point where I have a DataTable with all those ID's whose update column is ticked.
I'm hopeful, I'm heading in the right direction. Comment if I'm not
Further Update:
I've now create a stored procedure which accepts UserDefinedTableType and a destinationOwnerID as parameter and updates the actual table with the supplied OwnerID for all those leads whose ID matches the records from DataTable.
Create Procedure [activity].[udpUpdateActivityLead]
#ActivityLeadTable ActivityLeadType READONLY,
#OwnerTo int
AS
BEGIN
UPDATE [activity].[tblActivity]
set [activity].[tblActivity].[IDOwner]= #OwnerTo
from #ActivityLeadTable
where [activity].[tblActivity].[ID]=[#ActivityLeadTable].[ID];
END
Finally I got this function in my UI which works like a GEM. Happy ending...I can go to sleep now...
public void updateActivityLead()
{
SqlConnection con = new SqlConnection(OpSupLib.MyConnectionString);
SqlCommand cmd = new SqlCommand();
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "[activity].[udpUpdateActivityLead]";
SqlParameter p1 = new SqlParameter();
p1.ParameterName = "#ActivityLeadTable";
p1.Value = getDataGridID();
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter();
p2.ParameterName = "#OwnerTo";
p2.Value = ((ComboBoxItem)cmbUpdateTo.SelectedItem).HiddenValue;
cmd.Parameters.Add(p2);
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}

C# Fill combo box from SQL DataTable

DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
There was an Error...
The result is System.Data.DataRowView instead of data from database..
I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.
You could also specify DisplayMember property of combobox to any of the column name.
For example if you want to display Name field, you could do
Combobox1.DisplayMember="Name";
I think the problem is that you are trying to insert multiple columns into a comboBox (which can accept only one column). Adjust your SELECT statement so that it combines all of the data you need into one column:
Example:
SELECT Name + ' ' LastName + ' '+ ID AS 'DoctorData' FROM Doctor
By using the + operator you can combine multiple columns from the database, and represent it as a single piece of data. I think that your code should work after that (you can even comment the foreach loop, I think that adding data source to your comboBox will be enough)

Must declare the scalar variable in C#

I am developing an app in C# in which when I am interacting with my database SQL Server
it is giving me the exception of 'Must declare the Scalar Variable'. The code is following
public DataTable Search(string clas)
{
try
{
DataTable table = new DataTable();
string query = "";
using (SqlConnection connection = new SqlConnection(connectionString))
{
if (clas != "")
{
query = "Select * from StudentManagement Where classEnrolled=#cls";
//dataAdapter
dataAdapter = new SqlDataAdapter(query, connectionString);
dataAdapter.SelectCommand.Parameters.Add(new SqlParameter("cls", clas));
}
dataAdapter = new SqlDataAdapter(query, connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
}
return table;
}
catch (Exception e)
{
return null;
}
}
Please help me
I have a strong suspicion that clas is a null reference. Note that this will still trigger your != "" branch, since a null-reference is not the same as an empty string.
Maybe use:
if(!string.IsNullOrEmpty(clas)) {...}
Instead?
A peculiarity of db-parameters is that they are not included if the .Value is null. Check the value you are sending in.
It doesn't apply in your case (since in normal SQL nothing ever equals NULL) but: if you intend to send NULL as a parameter, you must set the value to DBNull.Value instead.

Categories