Select 2nd column of stored procedure's output - c#

My stored procedure returns this
1 skl meter 50
I want my c# program to select the skl from the output.
I am currently doing this
SqlDataReader dr=comm.ExecuteReader();
var fal = dr.Read();
if (fal)
{
var skl = dr.GetString(1);
}
and it doesn't work.
How would I select Skl or any other value from a sql output?
The problem is it selects skl even if skl isn't present in the output

If your Procedure Returns more than 1 row of data, then I would suggest binding to a Datagrid.
This way you can also view the output and is a (ui) way of debugging.
Once you have the datagrid view showing your rows of data I would then do something like this:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if(row.Cells["Name of the field"].Value != DBNull.Value)
{
string Myval = row.Cells["Name of the field"].Value;
}
}
But this is a long way of doing it and checking. To be Honest the method your using I think should work, Are you Receiving an error? or is the value wrong?

You need to check for null and hasrows
if(rdr.HasRows)
{
rdr.read();
string strValue = string.Empty;
if (!rdr.IsDBNull(1)) strValue = rdr.GetString(1);
}
else {} // woops

Related

Get rid of all null values in Combobox after iport data from mysql database

I'm developing some winforms application for my office. in my application I have more than 50 comboboxes that I want to connect the MySQL database and retrieve data. every combobox should retrieve data from certain MySQL database column. any way I successfully made a connection and retrieve data to comboboxes using below code.
but now I have very strange problem. in my MySQL database there are lot of null values (some columns contain 30 rows while some only 1 or 2). after data retrieves the comboboxes the first combobox (which related to second column) display data correctly but start from 2nd column it shows only one or two rows. all the other values in column not showing. I went through some forums and set my al null values to empty string. but after that comboboxes shows me list of blank entries after last field.
I also tried IS NOT NULL after my query, that also not working :(
how to overcome this situation ? I want to retrieve data to all the comboboxes and without any empty or null values. I'm using .net framework 2.0
is this possible to programmatically in C# or SQL query, or should I change my database structure ?
(I don't have good knowledge in MySQL. I use workbench for create database :( )
This is my current code
void combobox()
{
string constring = string.Format("datasource='{0}';port='{1}';database='{2}';username=****************;password=************;Connect Timeout=180;Command Timeout=180", dbserverip.Text,curport.Text,currentdb.Text);
string Query = "select * from estifdb.customconditions ;";
MySqlConnection conn = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader myreader666;
try
{
conn.Open();
myreader666 = cmd.ExecuteReader();
while (myreader666.Read())
{
string sName = myreader666.GetString("someval1");
applicationcombobox.Items.Add(sName);
string sName2 = myreader666.GetString("someval2");
applicationcombobox2.Items.Add(sName2);
string sName3 = myreader666.GetString("someval3");
applicationcombobox3.Items.Add(sName3);
string sName4 = myreader666.GetString("someval4");
applicationcombobox4.Items.Add(sName4);
string sName5 = myreader666.GetString("someval5");
applicationcombobox5.Items.Add(sName5);
// and 50 left
I think you need something like that:
while (myreader666.Read()) {
for (int i = 0; i < myreader666.FieldCount; ++i) {
if (reader.IsDBNull(i))
continue;
String fieldName = myreader666.GetName(i);
String fieldValue = myreader666.GetValue(i).ToString();
//TODO: write a method to find out ComboBox by field name
ComboBox combo = GetComboByFieldName(fieldName);
if (combo != null)
combo.Items.Add(fieldValue);
}
}
you have to implement a method for finding out the right ComboBox by its field name
Have you also tried something like this:
string sName = myreader666.GetString("1003");
if(sName != null && !sName.Equals(""))
applicationcombobox.Items.Add(sName);
Tried using ABS, as in SELECT ABS(column_name) AS AbsoluteA FROM YourTable
if(myreader666.GetString("someval1") != null)
{
string sName = myreader666.GetString("someval1");
applicationcombobox.Items.Add(sName);
}
You can do this. Probably you don't want to add empty.string to the comboBoxes too. In this case add to the if(myreader666.GetString("someval1") != null && myreader666.GetString("someval1").Trim() != "")
Your design is bad you can check the answer with the for loop !
EDIT:
if(myreader666.GetString("someval1") != null)
{
string sName = myreader666.GetString("someval1");
applicationcombobox2.Items.Add(sName);
}
if(myreader666.GetString("someval2") != null)
{
string sName2 = myreader666.GetString("someval2");
applicationcombobox.Items.Add(sName2);
}
and so on for every someval

returning text values from CheckBoxList

I'm fairly new to coding so am probably missing something obvious. I've tried searching here and various other resources but can't get my code to do what I want so I'm hoping someone can help.
I have a checkbox list which is populated from a SQL query based on user input.
My intention is that a user can check one or more items on the list and a SQL stored Procedure will be run for each checked item with the value of the selected item passed as a parameter value.
So, if there are six items in the list and three are checked my code will loop through the list and for each checked item will run the SP with the item's value as the parameter value before moving on to the next item in the list.
As a first step in testing the logic I have the code below which is supposed to pass a selected item's text to a label when a button is clicked, however rather than the checked box's text value I am just getting 'System.Data.DataRowView'
int checkCount = chckList.Items.Count;
for (int i = 0; i < checkCount; i++)
{
if (chckList.GetItemChecked(i))
{
String str = chckList.Items[i].ToString();
label23.Text = str;
}
}
If I change the assignment of the String str value to 'String str = chckList.GetItemText(i).ToString();' I just get the number of the item (i.e. if there are six values and the fist is checked then I get '0', if the second is checked I get '1', etc.)
The CheckBoxList is, as I've said, filled from a SQL query based on user input, my method for doing this is:
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable datTbl = new DataTable();
adapter.SelectCommand = myCommand;
{
adapter.Fill(datTbl);
chckList.DataSource = datTbl;
chckList.DisplayMember = datTbl.Columns[1].ColumnName;
}
}
connection.Close();
Can anyone help? What am I doing wrong?
Thanks
If your Items are a collection of DataRowView objects, then this just gets a specific DataRowView and calls ToString() on it, which returns the fully qualified name of the object:
String str = chckList.Items[i].ToString();
Try accessing a specific column:
String str = ((DataRowView)chckList.Items[i])["SomeColumnName"].ToString();

Using GetSchemaTable() to retrieve only column names

Is it possible to use GetSchemaTable() to retrieve only column names?
I have been trying to retrieve Column names (only) using this method, is it possible.
DataTable table = myReader.GetSchemaTable();
foreach (DataRow myField in table.Rows)
{
foreach (DataColumn myProperty in table.Columns)
{
fileconnectiongrid.Rows.Add(myProperty.ColumnName + " = "
+ myField[myProperty].ToString());
}
}
This code retrieves a lot of table data unwanted, I only need a list containing
column names!:
You need to use ExecuteReader(CommandBehavior.SchemaOnly)):
DataTable schema = null;
using (var con = new SqlConnection(connection))
{
using (var schemaCommand = new SqlCommand("SELECT * FROM table", con))
{
con.Open();
using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
schema = reader.GetSchemaTable();
}
}
}
SchemaOnly:
The query returns column information only. When using SchemaOnly, the
.NET Framework Data Provider for SQL Server precedes the statement
being executed with SET FMTONLY ON.
The column name is in the first column of every row. I don't think that it's possible to omit the other column informations like ColumnOrdinal,ColumnSize,NumericPrecision and so on since you cannot use reader.GetString but only reader.GetSchemaTable in this case.
But your loop is incorrect if you only want the column names:
foreach (DataRow col in schema.Rows)
{
Console.WriteLine("ColumnName={0}", col.Field<String>("ColumnName"));
}
Change your code to below if all you want is to display the column names. Your original code was trying to not only display column names, but also trying to display the actual data values as well.
DataTable table = myReader.GetSchemaTable();
foreach (DataRow myField in table.Rows)
{
foreach (DataColumn myProperty in table.Columns)
{
fileconnectiongrid.Rows.Add(myProperty.ToString());
}
}
This will give you all column names, you can place them in a string[] and do with them what you like.
foreach(var columnName in DataTable.Columns)
{
Console.WriteLine(columnName);
}
//Retrieve column schema into a DataTable.
schemaTable = reader.GetSchemaTable();
int index = schemaTable.Columns.IndexOf("ColumnName");
DataColumn columnName = schemaTable.Columns[index];
//For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
{
String columnNameValue = myField[columnName].ToString();
Console.WriteLine("ColumnName " + columnNameValue);
}
I use same technics to add MAX-STRING-LENGTH constraint on custom TextBox in my VB.Net program.
I use a SQL SELECT command to get 4 column's values
SELECT code_pays
,nom
,code_pays_short
,default_devise
FROM pays
ORDER BY nom
I use the result returned by an IDataReader object to fill a DataGridView.
And finally, I display each row's field in a Panel that contains 4 TextBox.
To avoid that SQL UPDATE command used to save some record's changes done in TextBox return error message due to column value too long, I have added a property in custom Textbox to inform directly user that value's size is overlapped.
Here is my Form
Here is VB.Net code used to initialize MaxStringLength properties
Private Sub PushColumnConstraints(dr As IDataReader)
Dim tb As DataTable = dr.GetSchemaTable()
Dim nColIndex As Integer = -1
For Each col As DataColumn In tb.Columns
If col.ColumnName = "ColumnSize" Then
nColIndex = col.Ordinal
Exit For
End If
Next
If nColIndex < 0 Then
oT.ThrowException("[ColumnSize] columns's index not found !")
Exit Sub
End If
txtCodePays.MaxStringLength = tb.Rows(0).Item(nColIndex)
txtPays.MaxStringLength = tb.Rows(1).Item(nColIndex)
txtShortCodePays.MaxStringLength = tb.Rows(2).Item(nColIndex)
txtDefaultDevise.MaxStringLength = tb.Rows(3).Item(nColIndex)
End Sub
In For loop, program search index of field contained in ColumnSize column's value.
MaxStringLength property is assigned using following syntax
tb.Rows(%TEXT-BOX-INDEX%).Item(nColIndex)
.Rows(%TEXT-BOX-INDEX%) is used to identify column's metadata in SQL SELECT !
.Item(nColIndex) is used to get a specific column's metadata value
Item(n) can return a String or an Integer but VB.Net do implicit conversion when necessary.
This line of code can also be written shortly
tb.Rows(%TEXT-BOX-INDEX%)(nColIndex)
tb(%TEXT-BOX-INDEX%)(nColIndex)
but it is not readable !
Caution: MaxStringLength is a custom property. It is not part of normal TextBox.
In print screen above, you can see that program indicates to user that length is too big for Code Pays (3 lettres) TextBox.
Error's message is displayed in StatusBar at bottom of Form.
This information is displayed before clicking on SAVE button that generates an SQL UPDATE command.
Code used that call PushColumnConstraints method is following
Public Sub FillPanel()
SQL =
<sql-select>
SELECT code_pays
,nom
,code_pays_short
,default_devise
FROM pays
ORDER BY nom
</sql-select>
Dim cmd As New NpgsqlCommand(SQL, cn)
Dim dr As NpgsqlDataReader
Try
dr = cmd.ExecuteReader()
Catch ex As Exception
ThrowException(ex)
End Try
Call PushColumnConstraints(dr)

DataReader is null or empty

Using C#
I have a datareader that return a lsit of records from a mysql database.
I am trying to write code that checks if the datareader isnull. The logic behind this is: If the datareader having field then display the info otherwise hide the field.
I have tried:
cmd1 = new OdbcCommand("Select * from tb_car where vehicleno = '" + textbox2.text + "';", dbcon);
dr1 = cmd1.ExecuteReader();
if (dr1["tb_car"]. != DBNull.Value)
{
textbox1.Text = "contains data";
}
else
{
textbox1.Text = "is null";
}
The above code gives me this error:
Exception Details: System.IndexOutOfRangeException: Additional
Any help would be greatly appreciated...
I see a few problems here... First, it looks like you're trying to access the table name in the line:
if(dr1["tb_car"] != DBNull.Value
You should be passing a FIELD NAME instead of the table name. So if the table named "tb_car" had a field called CarId, you would want to have your code look like:
if(dr1["CarId"] != DBNull.Value)
If I'm right, then there is probably no field named "tb_car", and the Index is Out of Range error is because the DataReader is looking for an item in the column collection named "tb_car" and not finding it. That's pretty much what the error means.
Second, before you can even check it , you have to call the DataReader's Read() command first to read a line from the database.
so really your code should look like...
while(dr.Read())
{
if(dr1["CarId"] != DBNull.Value)
{
....
and so on.
See here for the proper use of a DataReader: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx
Finally, if you're just checking to see if there are any rows in the table, you can ignore all of the above and use the HasRows property as in
if(dr.HasRows)
{
....
although if you're using the while(dr.Read()) syntax, the code in the while loop will only execute if there are rows in the first place, so the HasRows could potentially be unnecessary if you don't want to do anything with no results. You would still want to use it if you want to return a message like "no results found", of course..
Edit - Added
I think there's a problem also with the line
if(dr1["CarId"] != DBNull.Value)
You should be using if DataReader's IsDbNull() method. as in
if(dr.IsDbNull("CarId"))
Sorry I missed that the first time around.
Use dr1.Read() to check that there is a row before attempting to read values. Read gets the first row initially, and then returns subsequent rows, returning true if row available or empty/end of set.
eg.
// for reading one row
if (rd1.Read())
{
// do something with first row
}
// for reading thru multiple rows
while (rd1.Read())
{
// do something with current row
}

how to populate textboxes with values of datareader

i have some textboxes. in first textbox i entered a vaue like empid. after the clicking a button which goes to database and checks for the columns specified by me.
i get that data in datareader.
from datareader i need to display the particular employ information in the remaining textboxes.
how can i achieve this.
Assuming your datareader is called rdr, something like this would work:
while(rdr.Read())
{
txtBox1.Text = rdr.Item["DBFieldName1"].ToString();
txtBox2.Text = rdr.Item["DBFieldName2"].ToString();
}
while (dr.Read())
{
string checkValue = dr.GetValue(0).ToString();
if (checkValue == myEmpIdTextbox.Text)
{
Texbox2.Text = dr.GetValue(1).ToString();
Texbox3.Text = dr.GetValue(2).ToString();
}
}
Works in C# - Visual Studio 2015.
The values in the brackets () next to GetValue indicate the column number, relative to your SQL Select query.
EXAMPLE:
SELECT coloumn1, coloumn2, coloumn3 FROM table
Then, in this case, Textbox3.Text will be made equal to the data in coloumn3, and Textbox2. Text to coloumn2, for that row where coloumn1 is equal to your value in your Empid textbox.

Categories

Resources