c# converting from System.Data.DataRowView to string - c#

i have a combobox whose datasource is a datatable. i need to loop through the items in the combobox, but how would i do this? i need to be able to convert each object of type 'System.Data.DataRowView' to string. any advice greatly appreciated!#

Based on your recent questions, it sounds like you are trying to figure out how to find or set the selected item in the combobox based on the text displayed in the item. I am not exactly sure how you have things set up, but please look at the following code and see if it helps:
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
dt.Rows.Add(3, "C");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
// use SelectedValue to select the item with ID == 2
comboBox1.SelectedValue = 2;
// use FindStringExact() to find the index of text displayed in the item
comboBox1.SelectedIndex = comboBox1.FindStringExact("C");
}
and using a combobox as set up above, you can get the text of the display member like this:
private void button2_Click(object sender, EventArgs e)
{
foreach (var item in comboBox1.Items)
MessageBox.Show(((DataRowView)item)["Name"].ToString());
}

Workaround for the same, hope it helps:
Convert the dataview source back to datatable and then loop through it.
DataView dt = (DataView)comboBox1.DataSource;
DataTable s = dt.Table;
foreach(DataRow dr in s.Rows)
MessageBox.Show(dr[0].ToString());

Well... to loop through a combobox, use (slightly pseudocoding, please don't c+p without working on the code):
var newItems = new List<string>();
for(var i = 0; i < combobox1.Items.Count; i++)
{
newItems.Add(combobox1.items[i].Text);
}
Then to access each item, use:
foreach(item in newItems)
{
var newVariable1 = item;
}
More info and your current code would be cool, I'd be able to help you more specifically with your problem that way.

Solution:
DataTable DtShow=new DataTable();
for (int i = 0; i < DtShow.Rows.Count; i++)
{
Console.WriteLine(DtShow.Rows[i].Field<string>(0));
}
** Field<string>(0) Column number start from 0

Hope this helps someone some day. Took me a while to come up with a solution for making a checkedboxlist populate from SQL server.
public partial class MemberSearch : Form
{
List<string> DataList = new List<string>(1);
public void GetTypesTable()
{
var CONEX = Properties.Settings.Default.Server_1_Conn;
var sql = "SELECT Type_List FROM List_Member_Types;";
DataTable dt = new DataTable();
using (SqlConnection c = new SqlConnection(CONEX))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
sda.Fill(dt);
DataView view = new DataView(dt);
DataTable s = dt;
foreach (DataRow ROW in s.Rows)
DataList.Add(ROW[0].ToString());
ckLstBox_MemTypes.DataSource = DataList;
}
}

Related

bind asp.net gridview column form textbox value dynamically

I want to bind gridview column from textbox value for example: I have two textbox and a button what i exactly want that i will give input in the two textboxes and when i clicked the button the textbox values will show in gridviw and want to do this for multiple times without replacing the previous values.
I found so many relevant answer but all are done with hard code inside button click event
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name",
typeof(string)),
new DataColumn("Age", typeof(decimal)) });
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind()
}
which replace the previous values when i insert new values, but i want to keep all the previous values in which I stuck .thanks
this code will help you to get current data from gridview to datatable
and then you can append new rows accordingly .
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt =GetGridData();
dr = dt.NewRow();
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private DataTable GetGridData ()
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
return _dataTable;
}
You can store the values from each PostBack into a Session or ViewState, otherwise you'll lose all the data when the button is clicked again.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt;
//check if the datatable already exists in the viewstate, if not create a new datatable
if (ViewState["myTable"] == null)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(decimal)) });
}
else
{
//correct viewstate exists, cast back to a datatable
dt = ViewState["myTable"] as DataTable;
}
//add the new values
dt.Rows.Add(TextBox1.Text, Convert.ToDecimal(TextBox2.Text));
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//save the datatable into the viewstate
ViewState["myTable"] = dt;
//clear the textboxes
TextBox1.Text = "";
TextBox2.Text = "";
}

My aim is to extract column names from a datable and put them in a dropdownlist in aspx. Facing issues

I am storing some column headers from an excel worksheet to a data table and extracting those column names/headers to populate my dropdown list in the aspx page. But sometimes I'm getting System.Data.DataRowView and sometimes it shows "Modified". I am using my datatable as DataSource for this Dropdownlist and the databinding is regularly failing. Can anyone help me with the code? Just a specimen so as to check where I am going wrong?
Here's the code:
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable(); //Datatable data from excel file
ListItem l = new ListItem();
for (int i = 0; i < dt.Columns.Count; i++)
{
DropDownList1.DataSource = dt;
l.Text = (dt.Columns[i].ColumnName).ToString();
l.Value = (dt.Columns[i].ColumnName).ToString();
DropDownList1.DataTextField = l.Text;
DropDownList1.DataValueField = l.Value;
DropDownList1.Items.Add(l);
DropDownList1.DataBind();
}
}
}
}
You don't need to add the items to the dropdownlist if you set the datatable as datasource, as this action will do that for you. You just have to set the property that will display the desired text and the hidden value of each item. Since I don't know the structure of your Datatable, I will post a sample code of my project:
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT Id, Name FROM Projects"), cn);
da.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
This operation will already add all the items stored in the datatable into the dropdownlist
EDIT: If the DataTable structure is dynamic/unknown, you will have to add the items by using a loop such as this:
DropDownList1.Items.Clear();
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable(); //Datatable data from excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
//Now depending on whether you will have to access them by value or not:
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName)); //Without Value
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName, i)); //With a numeric value that will serve like an index
}
DropDownList1.Items.Clear();
DataTable dt = new DataTable();
ExcelPackage package = new ExcelPackage(FileUpload1.FileContent);
dt = package.ToDataTable(); //Datatable data from excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
//Now depending on whether you will have to access them by value or not:
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName)); //Without Value
DropDownList1.Items.Add(new ListItem(dt.Columns[i].ColumnName, i)); //With a numeric value that will serve like an index
}

Display gridview columns based on user selection

I have a Gridview and want to make header dynamically based on user selection.
How to create headers that's been selected from users.
DataTable will help you to achieve. Please follow the code below
DataClassesDataContext db = new DataClassesDataContext();
protected DataTable GetDataSource()
{
DataTable dt = new DataTable();
var questions = db.ExecuteQuery<string>("select question from quiz where quizid is 123").ToList();
// Header implementation
int count = 0;
foreach (var question in questions)
{
DataColumn dc = new DataColumn(question);
dt.Columns.Add(dc);
count++;
}
// Rows implementation here
DataRow row = dt.NewRow();
...
dt.Rows.Add(row);
return dt;
}
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}

how to bind datatable to datagridview in c#

I need to bind my DataTable to my DataGridView.
i do this:
DTable = new DataTable();
SBind = new BindingSource();
//ServersTable - DataGridView
for (int i = 0; i < ServersTable.ColumnCount; ++i)
{
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
}
for (int i = 0; i < Apps.Count; ++i)
{
DataRow r = DTable.NewRow();
r.BeginEdit();
foreach (DataColumn c in DTable.Columns)
{
r[c.ColumnName] = //writing values
}
r.EndEdit();
DTable.Rows.Add(r);
}
SBind.DataSource = DTable;
ServersTable.DataSource = SBind;
But all i got is DataTable ADDS NEW columns to my DataGridView.
I don't need this, i just need to write under existing columns.
Try this:
ServersTable.Columns.Clear();
ServersTable.DataSource = SBind;
If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:
for (int i = 0; i < ServersTable.ColumnCount; ++i) {
DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.
// I built my datatable first, and populated it, columns, rows and all.
//Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.
BindingSource SBind = new BindingSource();
SBind.DataSource = dtSourceData;
ADGView1.AutoGenerateColumns = true; //must be "true" here
ADGView1.Columns.Clear();
ADGView1.DataSource = SBind;
//set DGV's column names and headings from the Datatable properties
for (int i = 0; i < ADGView1.Columns.Count; i++)
{
ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
}
ADGView1.Enabled = true;
ADGView1.Refresh();
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable StudentDataTable = new DataTable("Student");
//perform this on the Load Event of the form
private void AddColumns()
{
StudentDataTable.Columns.Add("First_Int_Column", typeof(int));
StudentDataTable.Columns.Add("Second_String_Column", typeof(String));
this.dataGridViewDisplay.DataSource = StudentDataTable;
}
}
//Save_Button_Event to save the form field to the table which is then bind to the TableGridView
private void SaveForm()
{
StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text});
dataGridViewDisplay.DataSource = StudentDataTable;
}
for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps :
step 1 - get all Users by :
public DataTable getAllUsers()
{
OracleConnection Connection = new OracleConnection(stringConnection);
Connection.ConnectionString = stringConnection;
Connection.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("semect * from Users");
cmd.CommandType = CommandType.Text;
cmd.Connection = Connection;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}
return dataSet.Tables[0];
}
step 2- set the return result to DataGridView :
public void setTableToDgv(DataGridView DGV, DataTable table)
{
DGV.DataSource = table;
}
using example:
setTableToDgv(dgv_client,getAllUsers());

loading combobox with datasource

i want to fill a combobox with data from the database when the page load
I had written the code as below
private void QuotationForm_Load(object sender, EventArgs e)
{
MessageBox.Show("hghjgvhg");
comboboxload();
}
public void comboboxload()
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("Select jobpk,jobecode from jobcodemastertable",oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("jobpk", typeof(int));
dt.Columns.Add("jobcode", typeof(string));
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
oleDbConnection1.Close();
}
it doesnot deturns an error or exception but doesnot load the combobox with data values
try this
comboBox1.DataSource = ds.Tables[0];
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "name";
You may need to bind datatable's view with combo box
cmbjobcode.DataSource = dt.DefaultView;
You're missing the DataBind method
dt.Load(reader);
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
cmbjobcode.DataSource = dt;
//here
cmbjobcode.DataBind();
oleDbConnection1.Close();
You have to call DataBind method on your combo. Thats why its not populating.

Categories

Resources