How to arrange the FieldName in AspxGridView? - c#

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.

Related

How to pull data from database and display in dropdownlist

I want to display details of a receipt number when the user enters the number and do a search. After the user should be able to edit the details. I pull the information for the driver; however, when I click to edit the list of drivers from the database is not shown; but just the actual data.
private void BindData()
{
int parsedValue;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
if (!string.IsNullOrEmpty(txtReceiptNo.Text.Trim()))
{
cmd.Parameters.Add("#receiptNo", SqlDbType.VarChar).Value = txtReceiptNo.Text.Trim();
}
cmd.Connection = sqlConn;
sqlConn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
String DATE = Convert.ToDateTime(dt.Rows[0]["returnDte"]).ToString("yyyy-MM-dd");
txtReturnDte.Text = DATE;
txtReceipt.Text = dt.Rows[0]["receiptNo"].ToString(); //Where ColumnName is the Field from the DB that you want to display
ddlCustomer.Text = dt.Rows[0]["CUSTNAME"].ToString();
//ddlDriver.Text = dt.Rows[0]["driverName"].ToString();
//ListItem lis = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlDriver.Items.Add(lis);
ddlUnitId.Text = dt.Rows[0]["unitId"].ToString();
txtNumber.Text = dt.Rows[0]["qtyReturned"].ToString();
txtLocation.Text = dt.Rows[0]["custLocation"].ToString();
//ddlDriver.DataSource = cmd.ExecuteReader();
//ListItem lis = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlCustomer.Items.Add(lis);
ddlDriver.DataSource = dt;
ddlDriver.DataBind();
ddlDriver.DataTextField = "driverName";
ddlDriver.DataValueField = "driverName";
ddlDriver.DataBind();
//ListItem li = new ListItem(dt.Rows[0]["driverName"].ToString());
//ddlDriver.Items.Add(li);
Panel1.Visible = true;
}
}
Your BindData() method is a good start, but it's little cluttered. And I am by no means an expert, but I'm going trim out some of the stuff you don't need for now and we'll see if we can get your drop down populated.
First you'll need to add a couple using directives at the top of your code behind page if they're not there already:
using System.Configuration;
using System.Data.SqlClient;
This is how I was shown:
private void BindData()
{
// Wrap the whole thing in a using() because it automatically closes the connection
// when it's done so you don't have to worry about doing that manually
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["name of your connection string"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
// Set the releveant properties like you already had
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PP_spSearchReturnCrate";
// Double check that the connection is open
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
// Create your SqlDataAdapter and fill it with the data from your stored procedure
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
// Then set that as the DataSource, and finally bind it to your drop down
ddlDriver.DataSource = ds.Tables[0];
ddlDriver.DataBind();
}
}
}
And if you'd like the default option in your drop down to say something other than whatever comes first from your stored procedure you can set a property called AppendDataBoundItems to true, then manually add a ListItem to your drop down, and set its Value to -1 (to get it to show at the top):
<asp:DropDownList runat="server" ID="ddlDriver" AppendDataBoundItems="true">
<asp:ListItem Enabled="true" Text="Please Select" Value="-1"></asp:ListItem>
</asp:DropDownList>

C# reading values from datatable filled with sql select

I am coding win form app, which checks on startup right of the currently logged user. I had these right saved in MS SQL server in the table. When importing data to Datatable, there is no problem. But when I want to read value, there is message "cannot find column xy".
SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);
DataTable dtRights = new DataTable(); //this is creating a virtual table
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
I would like, that program would save the value from SQL to int.
You are assuming that you have rows being returned, would be my first guess. You should loop through your DataTable instead of simply trying to access element 0 in it.
DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
Object cellValue = row[1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
}
using (SqlConnection con = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = #user"))
{
cmd.Parameters.AddWithValue("#user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
con.Open();
int right = Convert.ToInt32(cmd.ExecuteScalar());
}
}

A chart element with the name 'John' already exists in the 'SeriesCollection'

I am following this post, to build a bar chart and show on my webpage. Below is the code i have done to accomplish it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from ForChart";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet, "Query");
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
string YVal = Convert.ToString(row[columnName]);
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
GridView1.DataSource = myDataSet;
GridView1.DataBind();
cmd.Connection.Close();
And my table is having the below data. Please check the snapshot
But when i run the code i am getting the below error. Please help me to resolve the issue:
A chart element with the name 'John' already exists in the 'SeriesCollection'.
I am not able to traverse the records thats why i am getting this error, but i don't know how to traverse through all the records.
Coding help would be very much appreciated. Thanks.
I'm assuming that Chart1.Series requires unique names, and thus this call will fail when you try to enter the same name multiple times:
Chart1.Series.Add(seriesName);
Ugh, that entire example on MSDN is filled with bad practices:
select *
no usings used with SqlConnection, SqlCommand,...
mixing UI code and DB code (they should be in separate classes)
Look at this example for a possible solution.

DataAdapter Update issue

The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.

Retrieve records from Mysql database and display it in a combo box

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

Categories