I'm trying to build a simple page that will allow for bulk SQL Searches using a text area. The textbox is split on each new line and each line taken as a parameter to query. The resulting row is then added to a DataTable.
There isn't a problem with the query and the DataTable is built and returned as I expected when checked through debug mode. The only problem is when I attempt to bind the DataTable to the gridview , the gridview is left without rows.
I have been scratching my head at this for a hwile now and cannot figure out why the DataTable will not bind. The column names all match up but the actual table in result is unnamed. Is this an issue?
Here's the code.
ASPX:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="SIM NUMBER" HeaderText="SIM NUMBER" />
<asp:BoundField DataField="Voice" HeaderText="Voice" />
<asp:BoundField DataField="IMSI" HeaderText="IMSI" />
<asp:BoundField DataField="Tariff" HeaderText="Tariff" />
<asp:BoundField DataField="Contract Start" HeaderText="Contract Start" />
<asp:BoundField DataField="Supplier" HeaderText="Supplier" />
</Columns>
</asp:GridView>
And the C# Code:
public partial class Query : System.Web.UI.Page
{
protected static string numbers = "";
protected static string number;
protected static DataTable result = new DataTable();
protected static string simNumber;
protected static string voice;
protected static string IMSI;
protected static string tariff;
protected static string contractStart;
protected static string supplier;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
result.Reset();
result.Columns.Add("SIM NUMBER", typeof(string));
result.Columns.Add("Voice", typeof(string));
result.Columns.Add("IMSI", typeof(string));
result.Columns.Add("Tariff", typeof(string));
result.Columns.Add("Contract Start", typeof(string));
result.Columns.Add("Supplier", typeof(string));
numbers = TextArea1.Value.ToString();
search();
GridView1.DataSource = result;
GridView1.DataBind();
}
protected static void search()
{
string[] split = numbers.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (string line in split)
{
if (line == string.Empty)
continue;
number = line;
getSupplierInfo();
}
}
protected static void getSupplierInfo()
{
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
foreach (DataRow dr in DT.Rows)
{
simNumber = dr["SIM_NUMBER"].ToString();
voice = dr["Voice"].ToString();
IMSI = dr["IMSI"].ToString();
tariff = dr["Tariff"].ToString();
contractStart = dr["Contract_start"].ToString();
supplier = dr["Supplier"].ToString();
addRow();
}
}
protected static void addRow()
{
DataRow simResult = result.NewRow();
simResult["SIM Number"] = simNumber;
simResult["Voice"] = voice;
simResult["IMSI"] = IMSI;
simResult["Tariff"] = tariff;
simResult["Contract Start"] = contractStart;
simResult["Supplier"] = supplier;
result.Rows.Add(simResult);
}
}
Any help would be very much appreciated. I'm sure its something really simple that i'm missing.
Thanks
Try changing:
AutoGenerateColumns="false"
to:
AutoGenerateColumns="true"
I Think you can try like this in aspx file
<Columns>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Your_Field_Name") %>'></asp:Label>
</ItemTemplate>
</Columns>
and in cs file just fit below code
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
And now bind your Datatable to Grid View.
GridView1.DataSource = DT;
GridView1.DataBind();
Related
I have a dropdown inside a asp gridview to Filter based on the selected dates. But when I make a selection on the dropdown I get an error, MySql.Data.MySqlClient.MySqlException: Incorrect date value: '9/12/2018 12:00:00 AM' for column 'dateValue' at row 1.
Below would be the client side code:
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField>
<HeaderTemplate>
Date:
<asp:Label ID="lbldate" Text="date" Visible="false" runat="server"></asp:Label>
<asp:DropDownList ID="ddlgvdate" DataTextFormatString="{0:yyyy-MM-dd}" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate >
<asp:Label ID="lbldate1" runat="server" Text='<%# Eval("date", "{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
Below would be the server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
PopulateDropDown((cells.FindControl("ddlgvdate") as DropDownList), (cells.FindControl("lbldate") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
string date = null;
DateTime dateValue1 = Convert.ToDateTime(date);
string dateValue = dateValue1.ToString("yyyy-MM-dd");
dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = ViewState["Date"].ToString();
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvdate":
ViewState["Date"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below would be the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData1`
(in dateValue date)
BEGIN
SELECT *
FROM approved
WHERE
(dateValue IS NULL OR date = dateValue);
END
Please let me know how I can pass the date with the right format. Thanks in advance.
Thanks for John's suggestion I figured it out by using Nullable DateTime as shown below
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
DateTime? dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = DateTime.Parse(ViewState["Date"].ToString());
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}
I need shows the file names from a folder into a GridView control.
I thinked use the Directory class.
In my database I have the column sFolder with this value for each row:
control/Imp/foo
I have tried this tutorial on the web but I can't get the file names from a folder into a GridView control.
I don't have error but the GridView is empty even if the path to the folder is correct.
My code below.
Can you help me?
Thank you in advance for any help, really appreciated
.cs
dt2 = new DataTable();
ds2 = new DataSet();
sql = #String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
.aspx
<asp:GridView ID="gvDownload" EmptyDataText="Data empty"
runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
</asp:GridView>
#Edit 01
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
RetrieveProductsDowload();
}
private DataSet RetrieveProductsDowload()
{
dt2 = new DataTable();
ds2 = new DataSet();
sql = #String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
}
Please, try this:
string[] allfiles = Directory.GetFiles(FilePath, "*", SearchOption.AllDirectories);
gvDownload.DataSource = allfiles;
gvDownload.DataBind();
this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.
i've set up an userdefined connection string and now trying to populate a gridview using that,breakpoint shows connection string's fine..also no error,but surprisingly datatable is n't receiving any value..although data exists...what have i done wrong??
Default3.Aspx:
<td colspan="2" align="center">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
</asp:GridView>
</td>
Default3.Aspx.Cs:
protected void Page_Load(object sender, EventArgs e)
{
string con = OracleDatabase.connection();
String SelectCommand = "select * from EMP";
OracleDataAdapter adp = new OracleDataAdapter(SelectCommand, con);
DataTable dt = new DataTable();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
/*
OracleDatabase.gridpopulate(SelectCommand, GridView1);
GridView1.DataSource = OracleDatabase.gridpopulate(SelectCommand);
GridView1.DataBind();
*/
//i tried doing this by writting a function At class file also
}
Class file:
public static string connection()
{
oradb = ConfigurationManager.ConnectionStrings["ConnectionString"]
.ConnectionString;
string str = "Data Source="+db+";User ID="+userid+";Password="+password+";";
oradb = String.Concat(oradb, str);
con = new OracleConnection(oradb);
con.Open();
return oradb;
}
/*(function for gridpopulate)
public static void gridpopulate(string SelectCommand,GridView grid1)
{
string con =(ConfigurationManager.ConnectionStrings["ConnectionString"]
.ConnectionString);
con = String.Concat(con, str);
adp = new OracleDataAdapter(SelectCommand,con);
DataTable dt = new DataTable();
adp.Fill(dt);
grid1.DataSource = dt;
grid1.DataBind();
//return dt;
}
*/
Try as per below, instead of returning connection string from function return Oracle Connection object and pass the same to Adapter.
OracleConnection con = OracleDatabase.connection();
public static OracleConnection connection()
{
oradb =ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str = "Data Source="+db+";User ID="+userid+";Password="+password+";";
oradb = String.Concat(oradb, str);
con = new OracleConnection(oradb);
con.Open();
return con;
}
I have a GridView containing data extracted from two TextBoxes on click of a button. I want the following functionalities to be implemented in the Gridview:
1) I want to be able to Edit the data in this GridView.
2) I should also be able to Delete the rows from the GridView.
3) Finally, when I click on another Submit button, all the rows from the Gridview should be saved in the database.
Its a web-based ASP.NET application coded using C# (Visual Studio 2010), and uses SQL Server 2005. How can I make changes to the below code to implement the above specified functionality?
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
Session["data_table"] = dt;
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
ds.Clear();
da = new SqlDataAdapter("insert into PRACT values(#name, #city)", con);
con.Open();
da.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
con.Close();
}
}
Well on your aspx page I would recommend you to do that:
<asp:GridView runat="server" id="gvDisplay" OnRowCommand="grid_OnRowCommand">
<Columns>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtNameGrid" Text='<%#DataBinder.Eval(Container.DataItem, "Name")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtCityGrid" Text='<%#DataBinder.Eval(Container.DataItem, "City")%>'/>
</ItemTemplate>
</TemplateField>
<TemplateField>
<ItemTemplate>
<asp:Button runat="server" id="btnDeleteGrid" Text = "Delete" CommandArgument='<%#Eval(Container.DataItem, "YourIDColumn")%>' CommandName="DeleteRow"/>
</ItemTemplate>
</TemplateField>
</Columns>
</asp:GridView>
I recommend you to create a new column in your DataTable, this column will be the ID of each register.
Well, you add registers to this DataTable on your page, so you will need to create a session of type int and each time the event btnTextDisplay_Click is called you must increase this int Session and set it's value to the DataTable's Column ID.
The grid's attribute, OnRowCommand, is the event that will be called when you click on the button btnDeleteGrid. The code of this event comes below:
protected void grid_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "DeleteRow")
{
foreach(DataRow row in dt.Rows)
{
if(Convert.ToInt32(row["YourColumnID"]) == Convert.ToInt32(e.CommandArgument))
row.Delete();
}
dt.AcceptChanges();
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
Your event that will save the registers should be like that.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach(DataRow row in dt.Rows)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["constring"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO YOUR_TABLE_NAME (NAME, CITY) VALUES (" + row["Name"].ToString() + "," + row["City"].ToString() + ")";
int numRegs = cmd.ExecuteNonQuery();
}
}
I really expect I helped.
I can't test my code and I'm not so good on work with DataTables, so if there's any problem with my code, just let me know.
I think it will be more efficient if you use Bulk Inserts to realize the inserts. Search for how to make it, it's pretty cool and quick.
And also try to use Stored Procedures, because it's safer than use direct command texts. Using them will prevent SQL Injection.
Best regards.