I am having trouble figuring out how this DataMember should work.
It gives me the error 'Child list for field tbl1 cannot be created.'
I have tried tbl1, table1, text, table1_text etc.
What is the logic behind the DataMember and is it documented anywhere?
How do I selected certain fields to be shown?
string sql = "select * from table1 order by text"; // id, text
DataSet ds = new DataSet("tbl1"); // originally just ()
OdbcDataAdapter adapter = new OdbcDataAdapter(sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "tbl1"; // fails here
Update:
The answer is
dataGridView1.DataMember = "Table";
The next question is why?
What is the format and naming here?
Where is "Table" defined?
Related
I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", DateFromStr);
cmd.Parameters.AddWithValue("#DateTo", DateToStr);
//cmd.Parameters.AddWithValue("#DateFrom", "2015-01-01 00:00:00");
//cmd.Parameters.AddWithValue("#DateTo", "2015-12-31 23:59:59");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.
For Example:
select
student_id,student_name ,Class,School_Name
From
Student_Details
If above one is my stored procedure. I will get the Field Name how I mentioned in my query.
But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.
Is there anyway to arrange in AspxGridView?
Check my answer Based on my understanding of the question and #mohamed's comment.
Try to use the DataColumn.SetOrdinal method. For example:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
ds.Tables[0].Columns["Class"].SetOrdinal(1);
ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
ds.Tables[0].Columns["School_Name"].SetOrdinal(3);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
even if user changes the select statement order of columns will not change.
Use the hiddentext field and get the column names as user wants to display in which order.
string selectedColumns = HiddentxtSelectedColumn.Value;
Move the selectedColumns to array
string[] names = selectedColumns.Split(',');
sda.Fill(ds);
for (int i = 0; i < names.Length; i++)
{
ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
}
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
Now It will run exactly.
I have a little problem with populating my DevExpress Gridview, I want to have a two level gridview and using SqlCommand. At first I created a Dataset and added two tables and also defined relation for them. But it does not work. Can you help me find my problem?
Here is my code
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id] FROM [dbo].[OWNER]";
string property = "SELECT [number] ,[owner_ID] ,[GPSId] ,[Energy],[corp_type] ,[Pool],[irrigation] ,[variety] ,[trees] ,[utilizat] ,[address] ,[water_hour] ,[w_source] ,[w_inche],[w_dore],[NoeMalekiat],[MotevasetBardasht],[Area] ,[OBJECTID],[Shape] FROM [dbo].[Property] ";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
System.Data.DataSet dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
adapter.SelectCommand.CommandText = property;
adapter.Fill(dsMain, "Second Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Second Table"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
GridAttrebuteTable.DataSource = dsMain.Tables[2];
// gridView5.DataSource = dsMain.Tables[1];
dataGridView1.DataSource = dsMain;
I searched and found this http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx and it seems my code is right but it does not show anything in grids
Thank you very much for your help
I Could figure out how to fix it.It works fine now(Above Code is edited) but now If I add a new DataTable I do not know why it does not work again
You need a new GridView for each detail table. You can't display both a master and detail in the same GridView.
Try this example
I have a DbConnect class which queries a MySQL database and store the results into a datatable - something like this:
public DataTable selectCombo()
{
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now how to retrieve the datatable from the class into the combo box main form? Can I do something like this?
ComboBox1.DataSource = dbConnect();
ComboBox1.DisplayMember = "Name"; // column name to display
You have two variables with the same name. (dt) One is defined as a string, the other one inside the if block is defined as a datatable. You return the empty string and this, of course, cannot work when you try to assign the DataSource of the combo
public DataTable selectCombo()
{
DataTable dt = new DataTable();
string query = "SELECT DISTINCT month FROM printer_count";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
this.CloseConnection();
return dt;
}
Now you could write
....
ComboBox1.DisplayMember = "Name";
ComboBox1.DataSource = selectCombo();
.....
Also this code is not very safe. If, for any reason, you get an exception, the CloseConnection will not be called leaving an open connection around and this is very problematic for the stability of your system. However, fixing that problem, requires a different approach to you OpenConnection code. Instead of true this method should return the MySqlConnection object so your calling code could apply the using statement around the connection instance
Whenever I run my code and try to view a highscore all I get back in my listbox is System.Data.DataRowView.
Can anyone see why?
Code:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.DataSource = dTable;
I always have to deal with this problem, even if I set the DisplayMember and ValueMembers of the List Box.
Your current code is correct and should work, if you need access to the current selected item value of any column of your dTable you can get them doing this:
DataRowView drv = (DataRowView)lstNames.SelectedItem;
String valueOfItem = drv["NameAndScore"].ToString();
What I like about getting the entire DataRowView is that if you have more columns you can still access their values and do whatever you need with them.
The following code should work:
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dSet.Tables[0];
If it does not work, please update your question and provide us with some information about the columns and values that are actually returned in dSet.Tables[0].
Set your lstNames.DisplayMember and lstNames.ValueMember fields.
Gets or sets the property to display for this ListControl.
Gets or sets the path of the property to use as the actual value for
the items in the ListControl.
This should solve your problem..
Like I said in the comments, please add lstNames.DataBind() to your code.
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dAdapter.Dispose();
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
EDIT:
Can you try this instead:
MySqlConnection myConn = new MySqlConnection(connStr);
string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " +
"FROM highscore ORDER BY Score DESC";
myConn .Open();
SqlCommand cmd = new SqlCommand(sqlStr, SQLConnection1);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
lstNames.Items.Add(rd[0]);
}
rd.Close();
rd.Dispose();
myConn.Close();
If you want your list box to show values from an specific column of the data source use
lstNames.DataTextField = "SpecialColumnName";
I use :
foreach (DataGridViewRow row in _dataGridView.SelectedRows)
{
var rowObject = row.DataBoundItem as DataRowView;
var array = rowObject.Row.ItemArray;
}
Only the order of the calls is wrong. First set the DataSource and only after that set the display member:
lstNames.DataSource = dTable;
lstNames.DisplayMember = "NameAndScore";
I had the similar problem of picking a single value from a populated Listbox and getting System.Data.DataRowView.
I was able to solve it by casting the selected item to System.Data.DataRowView and then
accessing the Row and ItemArray subclasses:
var si = ListBox1.SelectedItem;
string val = ((System.Data.DataRowView)si).Row.ItemArray[0].ToString();
I know its an old question. Just thought it might be nice to add an update to the answers given already. I was looking for a solution to the same problem. I the realized it is in which order you place these 3 lines of code
lstNames.DisplayMember = "NameAndScore";
lstNames.ValueMember = "NameAndScore";
lstNames.DataSource = dTable;
It should use the datasource first. Then The value member and then the display member
As follow:
lstNames.DataSource = dTable;
lstNames.ValueMember = "NameAndScore";
lstNames.DisplayMember = "NameAndScore";
just make sure you are typing the name of field same as in datasource in other word it is a case sensitive
so :
Me.GridLookUpEdit1.Properties.DisplayMember = "cur_code"
is different than
Me.GridLookUpEdit1.Properties.DisplayMember = "CUR_code"
if you copied the object instead of placing as a new object it will do this. Try deleting the object and putting it back on. I had the same issue and this is what I did. Don't know why it worked, but it did.
Sometimes what might cause it is mis-spelt displaymember variable name.
I want to insert data grid using datatable and define the grid columns in a program. Please help me what`s wrong with this code???
Following error is occur "Unable to cast object of type System.String to type System.String[]"
enter code here
SqlConnection connection;
string query;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
DataRow dRows;
public void ViewGrid()
{
connection = new SqlConnection(ConnString);
try
{
connection.Open();
query = #"SELECT * FROM TBLWorkers";
//cmd = new SqlCommand(query, connection);
da = new SqlDataAdapter(query, connection);
ds = new DataSet();
da.Fill(ds, "Workers");
int MaxRows = ds.Tables["Workers"].Rows.Count;
label1.Text = MaxRows.ToString();
dRows = ds.Tables["Workers"].Rows[0];
// Create an unbound DataGridView by declaring a column count.
dataGridView1.ColumnCount = 4;
dataGridView1.ColumnHeadersVisible = true;
// Set the column header names.
dataGridView1.Columns[0].Name = "Recipe";
dataGridView1.Columns[1].Name = "Category";
dataGridView1.Columns[2].Name = "Main Ingredients";
dataGridView1.Columns[3].Name = "Rating";
object[] rows1 = new object[] { dRows[0].ToString(), dRows[1], dRows[2], dRows[3] };
foreach (string[] rowArray in rows1)
{
dataGridView1.Rows.Add(rowArray);
}
}
catch (Exception x)
{
MessageBox.Show(x.Message);
connection.Close();
}
}
I would say that rowArray is a string not a string[].
You're iterating through an object[] and treating the elements in that array as string[] and element 0 of that array is definitely a string and not a string[].
I think what you intend to do, based on what you've written, is insert a single row into the DataGridView, because that's all dRows holds is one table row. You're code is partially from the MSDN example here and if you look at how that example works, you'll see that they build up a bunch of string[] to add unbound rows to the DataGridView.
Is that what you want to do here? Add an unbound row? You've already got a DataTable. You could just use data binding to solve this rather than retrieving the data from the DB, then copying it into an object[] just to turn around and put it into an unbound DataGridView.
You could just do this:
string[] myRow = new string[] { dRows[0].ToString(), dRows[1].ToString(), dRows[2].ToString(), dRows[3].ToString() };
dataGridView1.Rows.Add(myRow);
and I think that would work. Didn't test it, but I think that'll do it. But I'd probably set up the data binding if I were doing it.