So I'm using a SQL data source that fires a Store procedure using the selected value of a drop down list as a parameter to return one of a multitude of differing tables. Then I have a gridview that uses this SQLdatasource as it's datasource to display the returned values.
What I want is to be able to get at the column names at run time so that I can use it in a later method. However the SQLDatasource doesn't seem to have a property to get at this data and when I try to get at the columns of the Datagridview after I databind it the gridview only shows a single column (the auto-generated select column). Is there a way to get at this?
I don't know about using the SQLDatasource, but you can do this easily in the codebehind if you load your data into a DataTable. E.g.
var dt = new DataTable();
var connectionString = "your connection string";
using (var db = new SqlConnection(connectionString))
{
var command = new SqlCommand("stored_procedure_name", db);
command.CommandType = CommandType.StoredProcedure;
db.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
}
var columns = dt.Columns;
Each column has a ColumnName property. You can use Linq to get the column names as an array:
var columnNameArray = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
Related
I have created a class, in which I am trying to pass query and return the data in a DataTable, but I am unable to pass a parameter to the SqlCommand.
My attempt:
OpenSqlConnection();
SqlCommand sqlCommand = new SqlCommand(inputQuery, sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("", "");
sqlCommand.ExecuteNonQuery();
DataTable dtResult = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
da.Fill(dtResult);
CloseSqlConnection();
return dtResult;
In the above code, I am passing SqlCommand as an input query.
How I am calling the above function.
stdFetchDt = new DBManager().GetRecordsByQuery("storedprocedurename");
stdDrop.DataSource = stdFetchDt;
stdDrop.DataBind();
Here DBManager is the class name and GetRecordsByQuery is the method name.
But I'm not able to pass value for sqlCommand.Parameters.AddWithValue("", "");.
My problem: I am unable to pass value in sqlCommand.Parameters.AddWithValue("", "");, because number of value may be multiple.
Please help me with this.
You can send your parameter string with values combined with ',' in C# and then separate theme in the stored procedure :
DECLARE #tags NVARCHAR(400) = 'clothing,road,,touring,bike'
SELECT value
FROM STRING_SPLIT(#tags, ',')
I have Created a class and passing OBJECT & VALUE using List argument.
public DataTable GetRecordsByQuery(string inputQuery, List<string> objectInput, List<string> valInput)
Here in inputQuery String, I am passing name of stored procedure and in objectInput passing object and in valInput passing its value.
I have a table that has a TypeID column, amongst others. This TypeID column is a foreign key to another table where type names are populated.
On my aspx page, I have a drop down list whose selected field I want to set to whatever Type Name that TypeID corresponds to.
The confusing part is that I am querying table that just has the TypeID so I can't say something like below since I don't have TypeDesc in this table.
ddl.SelectedItem.Text = dtType.Rows[0]["TypeDesc"].ToString();
The way I connect to database to populate the dropdownlist
string sqlType = "SELECT TypeID, TypeDesc FROM .......";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
{
SqlCommand comType = new SqlCommand(sqlType, con);
comType.CommandType = CommandType.Text;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dtType = new DataTable();
da.Fill(dtType);
con.Close();
ddl.DataTextField = "TypeDesc";
ddl.DataValueField = "TypeID";
ddl.DataSource = dtType;
ddl.DataBind();
}
After above code runs, ddl is successfully populated with items. This is ddl on the aspx side:
<asp:DropDownList ID="ddl" runat="server" />
After all this is over, I query database again with a different query that selects from a table that only has TypeID (as foreign key to the above table of types).
After i execute this new query, i have a TypeID. I want the ddl to make the selected item the one whose Value matches this TypeID.
I can get all this to work with
ddl.SelectedIndex = Convert.ToInt32(dt.Rows[0]["TypeID"])-1;
but that is assuming that ddl member index is same as TypeIDs. Shouldn't there be an easier way to do this?
use this code:
ddl.SelectedValue = Convert.ToInt32(dt.Rows[0]["TypeID"]);
or
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(dt.Rows[0]["TypeDesc"]));
I'm intercepting the RowDatabound event and using:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to get access to the unbound data source columns. It works fine on page load and when I apply a filter to the dataset. However, when I attempt to initate a sort on a GridView Column, I get :
Error: Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.Common.DbDataRecord'
I think I've traced the root issue back to the bind method used in the sort:
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (eventArgs != null)
{
DataSet SortedData = new DataSet();
ds.Tables[0].DefaultView.Sort = eventArgs.SortExpression + " " + GetSortDirection(eventArgs.SortExpression);
SortedData.Tables.Add(ds.Tables[0].DefaultView.ToTable());
GridView1.DataSource = SortedData;
}
else
{
GridView1.DataSource = ds;
}
GridView1.DataBind();
}
I remember this was a major pain to figure out because only Dataset had a Sort Property
Since you assign a DataSet to GridView1.DataSource, then the type of e.Row.DataItem in the RowDatabound event will be a DataRowView instead of a System.Data.Common.DbDataRecord. You need to change this:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to this:
DataRowView record = (DataRowView)e.Row.DataItem;
Instead of trying to sort the Dataset, I appended the sort direction and column from the viewstate to the query before binding it to the grid using SqlDataReader. Looks like I went out of my way to make a simple thing hard to begin with...
I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY
Is it possible to populate asp.net GridView with data and operate on those data without dataBinding, as it is possible with Winforms DataGridView?
You can set the data source to a datatable that you can build up in code with whatever you like.
var table = new DataTable();
table.Columns.Add("Column1");
table.Columns.Add("Column2");
var row = table.NewRow();
row["Column1"] = "test";
row["Column2"] = "test2";
table.Rows.Add(row);
GridView.DataSource = table;
GridView.DataBind();
You can also set a gridview's data source with a list:
var yourList = new List<YourRowStuff>();
get the list from a database query or build it up manually in code....
GridView.DataSource = yourList;
GridView.DataBind();