网格视图不显示结果
当选择 DataSource
以及用户从 DropDownList
中选择选项时,我想在运行时绑定 GridView
。但所选的表或连接未正确建立。 请检查以下代码并给我适当的解决方案。
public partial class index : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection();
string option = "";
protected void Page_Load(object sender, EventArgs e)
{
option = selectProductdropdown.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = option;
if (option == "Books")
{
Label3.Text = option;
conn.ConnectionString = ConfigurationManager.ConnectionStrings["booksconnectionstring"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter reader = new SqlDataAdapter(cmd);
DataSet s = new DataSet();
reader.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
conn.Close();
}
I want to bind GridView
at run time when the DataSource
is selected and when the user select a option from a DropDownList
. But the selected table or connection is not made properly.
Please check the following code and give me the appropriate solution.
public partial class index : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection();
string option = "";
protected void Page_Load(object sender, EventArgs e)
{
option = selectProductdropdown.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = option;
if (option == "Books")
{
Label3.Text = option;
conn.ConnectionString = ConfigurationManager.ConnectionStrings["booksconnectionstring"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter reader = new SqlDataAdapter(cmd);
DataSet s = new DataSet();
reader.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
conn.Close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题出在您的 page_load 事件中,您在其中为选项分配了一个值。当您单击该按钮时, page_load 将再次调用并且您的值将重置。
它应该是......
或者如果你喜欢的话会更好......
The problem is in your page_load event, where you are assigning a value to option. When you click the button, the page_load will call again and your value will reset.
it should be...
OR it would be better if you do like..
因为您可能在每次页面加载时清空选项。
because you are probably emptying option at each page load.
避免使用公共变量string option = "";
而是在点击事件中定义相同的变量并在那里获取选定的值
因为单击按钮时下拉列表将被重置(假设您没有在此处显示下拉绑定代码)
Avoid the public variable string option = "";
Instead define the same in the Click Event and get the selected value there
Because when the button is clicked the dropdown would be reset (assuming you have not shown the dropdown bind code here)