how to populate textboxes with values of datareader - c#

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.

Related

How to check if a cell in selected row in dataGridView is empty/null, using C#?

I'm trying to write a code, which checks if a cell in selected row in dataGridView is empty/null before the cell will be updated with a value. The code, which I wrote, works but no matter if there is a value in cell in selected row or not, the data are not updated. I have tried with this code:
if (dataGridView1.SelectedRows[0].Cells[1].Value == null)
{
try
{
String ConnectionString = #"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
SqlConnection myconnection = new SqlConnection(ConnectionString);
myconnection.Open();
DateTime primaryKey = Convert.ToDateTime(dataGridView1.SelectedRows[0].Cells[0].Value);
SqlCommand AddNumbeCommand = myconnection.CreateCommand();
AddNumbeCommand.CommandText = "UPDATE dbo.Vagter SET [ansatID] = #ansatID WHERE [Dato] = #dato";
AddNumbeCommand.Parameters.Add("#ansatID", SqlDbType.Int).Value = textBox1.Text;
AddNumbeCommand.Parameters.Add("#dato", SqlDbType.DateTime).Value = primaryKey;
AddNumbeCommand.ExecuteNonQuery();
myconnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("The cell is updated.");
}
}
else
{
MessageBox.Show("There is already a value in the cell.");
}
As I mentioned befor, the actual result is that no matter if there is a value in cell in selected row or not, the data are not updated. The expected result is that when a user select in dataGrdView a row where cell under column ansatID already has a value, write a value in textBox1, and press on ''Tilføj ansatID til vagten'', the he get error:"There is already a value in the cell.". If he will select a row where cell under column ansatID is empty, write a value in textBox1, and press on ''Tilføj ansatID til vagten'', then the SQL query will be executed and he gets message "The cell is updated." This is also shown on following picture:
With this condition you can access that specific column in the selected row, you missed the OwningRow part and you need to compare to an empty string and null just in case:
(string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == "" ||
(string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value == null
SelectedCells[0].OwningRow means the first selected row, Cells[1] means is the ansatID.
Gotta love winforms and its clarity.
Edit: As someone pointed out, you need to manually update the data in the datagrid in winforms, it is convinient to have a function like UpdateDatagrid() and call it every time you modify the DB.
You can use String.IsNullOrWhiteSpace((String)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value))

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();

storing sql query results to populate dropdownlist inside formview

I have a dropdownlist of zipcodes.
It is a really large list and takes too long to load from database. So, first I was looking for the best solution to try and cache or save this data when the website is first loaded so I can use it whenever needed. I tried a list and dictionary then setting the datasource in code behind but it wouldn't let me set the selected value.
It kept telling me that it couldn't bind to a control with no datasource. To make things more difficult the dropdownlist is inside a formview.
I am just not sure the best way to go about this. I am setting the datasource and values in the formview created method but my selected value comes from the formview datasource.
private Dictionary<int, string> CreateZipcodeList()
{
string connStr = ConfigurationManager.ConnectionStrings["KlamathAlgaeEntityDevConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
Dictionary<int,string> ziplist = new Dictionary<int,string>();
//Create CoreEntity Record
SqlCommand cmd1 = new SqlCommand(#"select zipcode.ZipCodeId, zipcode.zip + ', ' + city.name + ', ' + ISNULL(GeographicState.name,'') + ', ' + Country.name as zipstring
from zipcode left outer join City on ZipCode.CityId = city.CityId
left outer join GeographicState on ZipCode.GeographicStateId = GeographicState.GeographicStateId
left outer join Country on ZipCode.CountryId = Country.CountryId
order by country.name, GeographicState.name, city.name",
conn);
try
{
conn.Open();
SqlDataReader reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
ziplist.Add(reader.GetInt32(0), reader["zipstring"].ToString());
}
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return ziplist;
}
protected void AddressForm_ItemCreated(Object sender, EventArgs e)
{
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataSource = CreateZipcodeList();
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataTextField = "Value";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataValueField = "Key";
((DropDownList)AddressForm.FindControl("Zipcodeddl")).DataBind();
//((DropDownList)AddressForm.FindControl("Zipcodeddl")).SelectedValue = Eval("zipcodeid").ToString();
}
This populates the dropdown fine but when I try setting the selected value it says the control is not databound. This also doesn't store the dictionary anywhere so I need to call the function to load dictionary when ever I need it.
Ok, that is way too many records for a drop down. Why don't you allow the user to enter 5 numberic characters, and then do an search on your Database by that number. I can't think of any reason you would have to put the entire zip code list in a drop down since no one is going to manually click down to find the one they want. I don't think it servers a usefull purpose, but if there is one let me know and I will try to figure out a solution.
Thats how the post office does it.
Update
To make this work, you would have a TextBox where a user could enter the zip code they think it is. Give them a button to click to search for that zip code.
Do an sql query to your database looking for that Zipcode.Zip, and if found, bring back all the data you need.
If it is not found what I would do is start removing the last character and do another search with a modified query with "Zipcode.Zip like '%modifiedZipCode%', and bring back the closest 10 or so options, and put those in a drop down menu.
If you remove one digit and the database could not find it you could go as far as you want removing characters, and rerunning the query until you got 10 or however many records you want. At some point removing digits will become pointless because the user obviously entered an incorrect zip code.

Select 2nd column of stored procedure's output

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

Getting data from MySQL connection and showing it on a TextBox

I have created a MySQL table. I can insert Data but now I'd like to get the saved data after I enter it into another tab's TextBox in my Windows Application in c# language.
I have coded the button "Refresh" to get the data, but I dont know if its correct or not. Basically I want to click it, get the data from the table, and post it at the textbox.
Here is what I got so far for the getting data part:
private void button3_Click(object sender, EventArgs e)
{
string clanname, date, type, rules, final;
string connString = "Server=localhost;Database=request;Uid=root;Pwd=;";
using (MySqlConnection mcon = new MySqlConnection(connString))
using (MySqlCommand cmd = mcon.CreateCommand())
{
mcon.Open();
cmd.CommandText = "SELECT * FROM requesttcw";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
clanname = textBox1.Text.Trim();
date = textBox2.Text.Trim();
type = textBox2.Text.Trim();
rules = textBox2.Text.Trim();
}
}
}
}
Please help!
Thanks
The Select query in your question is fetching data from your requesttcw table. You will want to read that data from your reader instance and add it to the appropriate text boxes. For instance, you could do something like this to get data:
//textBox1 will hold the value of the first row and first column of your database.
textBox1.Text = reader.GetString(0);
Updating the index in the GetString command above will change the column from which you are fetching data. So, you will have to update that index appropriately to fetch the proper data from your table and insert to the right text box's .Text property.
I don't know what type of data you are dealing with in your table. If the type is something other than string, you will want to use the appropriate Get function for the type, whether int, double, etc. Check out the MySqlDataReader reference page for more types.
Depending on the frequency of which your table layout changes, you may also want to use .GetOrdinal to get data using your reader. This command lets you specify a column name instead of its index. The above call could be changed to:
//assuming "clanname" is a column in your database
textBox1.Text = reader.GetString(reader.GetOrdinal("clanname");
Lastly, in your example you used
while (reader.Read()) { ... }
This will loop through each row in your query result set. I don't know how many text boxes you have or if you are looking for a specific format, but be aware that if you want to show data for a field from multiple rows in your text boxes, you will have to append to the Text property for each loop iteration.

Categories

Resources